A PHP code that finds the relative path of $b relative to $a

  • 2020-03-31 21:00:00
  • OfStack

PHP interview questions:
$a = '/ a/b/c/d/e.p HP'; $b = '/ a/b / 12/34 / c.p HP'; // calculate that the relative path of $b relative to $a should be.. /.. / c/d

Answers to PHP interview questions:

 
function getRelative($a,$b) { 
$arr = explode("/",$a); 
$brr = explode("/",$b); 
$c = count($arr)-2; 
$d = count($brr)-2; 
//Minus two, one is the file name that's not in the back,
//One is that the index of the array starts at 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)); 
} 


Related articles: