一道求$b相对于$a的相对路径的php面试题

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<=$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));
}

Leave Your Comment

Your email will not be published or shared. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="">

*
请输入图片中的字符以验证你并非垃圾机器人. 点击图片收听验证码的语音版.
点击这里收听此验证码的语音版本