Lets say I have these two directory paths:
"/www/website/news/old/"
"/www/library/js/"
I need a PHP function that would output a relative path from one directory to another. In this example it should output something like "../../../library/js/"
My Answer:
php
$dir1 = '/home/user/documents/folder1';
$dir2 = '/home/user/documents/folder2';
php
function getRelativePath($from, $to) {
$from = explode('/', $from);
$to = explode('/', $to);
$commonPath = [];
foreach ($from as $key => $value) {
if ($value === $to[$key]) {
$commonPath[] = $value;
} else {
break;
}
}
$relativePath = array_merge(array_fill(0, count($from) - count($commonPath), '..'), array_slice($to, count($commonPath)));
return implode('/', $relativePath);
}
echo getRelativePath($dir1, $dir2); // Output: '../folder2'
Rate this post
5 of 5 based on 3114 votesComments