PHP: Relative path between two directories

I need to calculate the relative path between two directories such that:

$a = "/one/two/three/four/";
$b = "/one/two/";

$a to $b has a relative path of ../../ and $b to $a has a relative path of three/four/. This function solves that problem very simply:

// Borrowed from http://php.net/manual/en/function.realpath.php#105876 and cleaned up
function relativePath($from, $to, $ps = DIRECTORY_SEPARATOR) {
    $arFrom = explode($ps, rtrim($from, $ps));
    $arTo   = explode($ps, rtrim($to, $ps));

    while(count($arFrom) && count($arTo) && ($arFrom[0] == $arTo[0])) {
        array_shift($arFrom);
        array_shift($arTo);
    }

    return str_pad("", count($arFrom) * 3, '..' . $ps) . implode($ps, $arTo);
}
Leave A Reply
All content licensed under the Creative Commons License