function getRelativePath($a, $b) {
$returnPath = array(dirname($b));
$arrA = explode('/', $a);
$arrB = explode('/', $returnPath[0]);
for ($n = 1, $len = count($arrB); $n
if ($arrA[$n] != $arrB[$n]) {
break;
}
}
if ($len - $n > 0) {
$returnPath = array_merge($returnPath, array_fill(1, $len - $n, '..'));
}
$returnPath = array_merge($returnPath, array_slice($arrA, $n));
return implode('/', $returnPath);
}
var_dump(getRelativePath($a, $b));
//方法二
$a = "/a/b/c/d/index.php";
//echo basename($a,'.php');// 返回路径中文件名部分
//echo dirname($a);
$b = "/a/b/12/34/index2.php";
function getRelativePath($path1,$path2){
$p1 = dirname($path1);
$p2 = dirname($path2);
$arr1 = explode('/',$p1);
$arr2 = explode('/',$p2);
$diff_arr= array_diff($arr2,$arr1); //计算差集 注意这里 是谁相对谁的
$inter_arr = array_intersect($arr1,$arr2);//计算交集
$leng = count($inter_arr); //长度是以交集的为准 即求..部分
for($i=1;$i
$inter_arr[$i] = '..';
}
$merge_arr = array_merge($inter_arr,$diff_arr);
$fina_arr = implode('/',$merge_arr);
return $fina_arr;
}
var_dump(getRelativePath($a,$b));
//返回 string '/../../12/34' (length=12)
//如果改成$diff_arr= array_diff($arr1,$arr2); 就返回string '/../../c/d (length=12)
|