Home  >  Article  >  Backend Development  >  PHP code A PHP code to find the relative path of $b relative to $a

PHP code A PHP code to find the relative path of $b relative to $a

WBOY
WBOYOriginal
2016-07-29 08:43:281036browse

php interview question:
$a = '/a/b/c/d/e.php'; $b = '/a/b/12/34/c.php'; //Calculate $b The relative path relative to $a should be ../../c/d
Answer to the php interview question:

Copy the code The code is as follows:


function getRelative($a,$b) {
$arr = explode("/",$a);
$brr = explode("/",$b);
$c = count($arr)-2;
$d = count($brr)-2 ;
//The reason for subtracting two is that one is the file name that is not behind,
//The other is that the index of the array starts from 0, which is one less than the number of the first dimension in the array
$e = ($ c>$d) ? $c:$d;
$str1 = $str2 = '';
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)
{
$str1.='/'.$cur_a;
}
if ($j <= $d )
{
$str2 .="../";
}
}
}
return $str2.substr($str1,1,strlen($str1));
}

The above introduces the PHP code. A PHP code to find the relative path of $b relative to $a, including the content of PHP code. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement:
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