Home > php教程 > php手册 > 一道求$b相对于$a的相对路径的php代码

一道求$b相对于$a的相对路径的php代码

WBOY
Release: 2016-06-13 12:14:08
Original
1390 people have browsed it

php面试题的题目:
$a = '/a/b/c/d/e.php'; $b = '/a/b/12/34/c.php'; //计算出 $b 相对于 $a 的相对路径应该是 ../../c/d

php面试题的答案:

复制代码 代码如下:


function getRelative($a,$b) {
$arr = explode("/",$a);
$brr = explode("/",$b);
$c = count($arr)-2;
$d = count($brr)-2;
//之所以减二,一个是不在后面的文件名,
//一个是数组的索引是从0开始的,比数组中的第一维的个数要小一
$e = ($c>$d) ? $c:$d;
$str1 = $str2 = '';
for ($j=0;$j$cur_a = isset($arr[$j]) ? $arr[$j] : '';
$cur_b = isset($brr[$j]) ? $brr[$j] : '';
if ($cur_a == $cur_b) {
continue;
} else {
if ($j {
$str1.='/'.$cur_a;
}
if ($j {
$str2.="../";
}
}
}
return $str2.substr($str1,1,strlen($str1));
}

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template