A PHP code to find the relative path of $b relative to $a_PHP tutorial

WBOY
Release: 2016-07-21 15:34:52
Original
862 people have browsed it

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

Answer to the php interview question:

Copy 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 not behind The file name,
//One 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));
}

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/322328.htmlTechArticlephp interview question: $a = '/a/b/c/d/e.php'; $b = '/a/b/12/34/c.php'; //Calculate that the relative path of $b relative to $a should be ../../c/d Answers to PHP interview questions: Copy code The code is like...
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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!