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/"
Following function would do the job:
function getRelativePath($source, $destination) {
$sourceArray = [];
preg_match_all('/([^\/]+)/', $source, $sourceArray);
$destinationArray = [];
preg_match_all('/([^\/]+)/', $destination, $destinationArray);
$sourceArray = array_reverse($sourceArray[0]);
$destinationArray = array_reverse($destinationArray[0]);
$relative = [];
$hasPath = false;
foreach ($sourceArray as $path) {
for ($i = 0; $i < count($destinationArray); $i++ ) {
$to = $destinationArray[$i];
if ($path == $to) {
$hasPath = true;
for ($j = $i - 1; $j >= 0 ; $j--)
$relative[] = $destinationArray[$j];
break 2;
}
}
$relative[] = "..";
}
return $hasPath ? implode("/",$relative) . "/" : "NO PATH";
}
Here is a simple function given the source and destination exist:
function getRelativePath($source, $destination)
{
$paths =
array_map(fn ($arg) => explode('/', realpath($arg)), func_get_args());
return
str_repeat('../', count(array_diff_assoc(...$paths))) .
implode('/', array_diff_assoc(...array_reverse($paths)));
}
Nothing fancy. No check is implemented on the source being a folder and not a file.
Note: the destination can be a file while the source is supposed to be a directory from where the relative path is calculated.