The topic of the PHP interview question:
$a = '/a/b/c/d/e.php '; $b = '/a/b/12/34/c.php '; Calculate the relative path of the $b relative to the $a should be ... /.. /c/d
The answer to the PHP interview question:
Copy Code code as follows:
function getrelative ($a, $b) {
$arr = Explode ("/", $a);
$BRR = Explode ("/", $b);
$c = count ($arr)-2;
$d = count ($BRR)-2;
Minus two, one is not in the back of the file name,
One is that the index of an array starts at 0, smaller than the number of the first dimension in the array.
$e = ($c > $d)? $c: $d;
$str 1 = $str 2 = ';
for ($j =0; $j <= $e; $j + +) {
$cur _a = isset ($arr [$j])? $arr [$j]: ';
$cur _b = isset ($brr [$j])? $BRR [$j]: ';
if ($cur _a = = $cur _b) {
Continue
} else {
if ($j <= $c)
{
$str 1.= '/'. $cur _a;
}
if ($j <= $d)
{
$str 2.= ". /";
}
}
}
Return $str 2.substr ($str 1,1,strlen ($str 1));
}