PHP 计算两个文件的相对路径
答案
/**
* 找出path1相对于path2的路径
*/
function getRelativePath($path1, $path2)
{
$path1Arr = explode("/", $path1);
$path2Arr = explode("/", $path2);
$disMatch = 0;
for ($i = 0; $i < count($path1Arr); $i++) {
if ($path1Arr[$i] != $path2Arr[$i]) {
$disMatch = count($path1Arr) - $i;
$left = array_slice($path1Arr, $i);
break;
}
}
return str_repeat("../", $disMatch) . implode("/", $left);
}
测试代码:
$a = '/a/b/c/d/e.php';
$b = '/a/b/12/34/5.php';
echo getRelativePath($a, $b);
// 结果:../../../c/d/e.php