我的位置: 首页 > 学习专区 > PHP技术 > PHP面试题之[求相对路径]

PHP面试题之[求相对路径]

2013-01-23 14:30:40
来源:
[导读] 题目:写一个函数,算出两个文件的相对路径如 $a = ‘ a b c d e php’; $b = ‘ a b 12 34 c php’; 计算出

题目:写一个函数,算出两个文件的相对路径如 $a = ‘/a/b/c/d/e.php’; $b = ‘/a/b/12/34/c.php’; 计算出 $b 相对于 $a 的相对路径应该是 ../../c/d

function getRelative($a , $b)

{

$arr_a = explode(“/” , $a) ;

$brr_b = explode(“/” , $b) ;

$i = 1 ;

while (true) {

if($arr_a[$i] == $brr_b[$i]) {

$i ++ ;

} else {

break ;

}

}

$c = count($brr_b) ;

$d = count($arr_a) ;

$e = ($c>$d)?$c:$d ;

$str1 = ” ;

$str2 = ” ;

for ($j = $i ;$j<$e ;$j++) {

if(isset($arr_a[$j])) {

if($j<($d-1)){

$str1 .= $arr_a[$j] . “/” ;

} else {

$str1 .= $arr_a[$j] ;

}

}

if(isset($brr_b[$j])) {

$str2 .= “../” ;

}

}

return $str2 . $str1 ;

}

$a = “/c/b/c/d/k/h/t/e.php” ;

$b = “/a/b/e/f/h.php” ;

$relative = getRelative($a,$b) ;

var_dump($relative);

?>

运行结果:string(34) “../../../../../c/b/c/d/k/h/t/e.php”

评论
热点专题
>>
相关文章推荐
>>