8.5.3 字符串面试题3
四、写一个函数,算出两个文件的相对路径
如:
$a=’/a/b/c/d/e.php’
$b=’/a/b/12/34/c.php’
计算出$b相对于$a的相对路径应该是../../c/d
test.php
<?php
function abspath($a, $b) {
//第一步去除公共的目录结构
// $a = "/a/b/c/d/e.php";
// $b = "/a/b/12/34/c.php";
$a = dirname($a); // /a/b/c/d
$b = dirname($b); // /a/b/12/34
$a = trim($a, "/"); // a/b/c/d
$b = trim($b, "/"); // a/b/12/34
$a = explode("/", $a); // array("a", "b", "c", "d")
$b = explode("/", $b); // array("a", "b", "12", "34")
// $a = explode("/", trim(dirname($a), "/"));
$num = max(count($a), count($b));
for($i=0; $i<$num; $i++) {
if($a[$i]==$b[$i]) {
unset($a[$i]);
unset($b[$i]);
}else{
break;
}
}
//$a = array("c", "d");
//$b = array("12", "34");
//第二步:回到同级目录, 进入另一个目录
$path = str_repeat("../", count($b)).implode("/", $a); // ../../c/d
return $path;
}
$a = "/a/b/c/d/e/w/f/e.php";
$b = "/a/b/12/34/100/c.php";
// ../../c/d
echo abspath($a, $b);