在網(wǎng)上看到一個面試題,求B路徑相對于A路徑的相對路徑,比如:
$a = '/a/e.php'紊册,
$b = '/a/b/c/d/1/2/c.php'
計(jì)算出的$b相對于$a的相對路徑應(yīng)該是:../b/c/d/1/2/c.php
$a = '/a/e.php';
$b = '/a/b/c/d/1/2/c.php';
// 求newPath相對于basePath的相對路徑
function getRelativePath($basePath, $newPath){
$relative = '';
$base_pathArr = explode("/", $basePath);
$new_pathArr = explode("/", $newPath);
$cnt_base = count($base_pathArr);
for($i = 0; $i < $cnt_base;$i++){
if($base_pathArr[$i] != $new_pathArr[$i]){
break;
}
}
if($i == $cnt_base){ //全匹配的話放前,單獨(dú)做處理,其實(shí)當(dāng)前文件夾下也可以不用
$relative = './';
}else{
$n = $cnt_base - $i;
for($j=0;$j<$n;$j++){
$relative = $relative."../";
}
}
$extraPath = implode("/", array_slice($new_pathArr, $i));
$relative_path = $relative.$extraPath;
return $relative_path;
}
$res = getRelativePath($a, $b);
var_dump($res);
輸出結(jié)果為:
string(18) "../b/c/d/1/2/c.php"