php教程 獲取相對路徑實例代碼
function getRelativePath($a, $b) {
$returnPath = array(dirname($b));
$arrA = explode('/', $a);
$arrB = explode('/', $returnPath[0]);
for ($n = 1, $len = count($arrB); $n < $len; $n++) {
&nb sp; 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<$leng;$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)