假如现在有两个路径:
$a = "/a/b/c/d/test.php";
$b = "/a/b/e/f/other.php";
请用PHP设计一个函数,计算出$b相对于$a的路径。
大致算法就是: 根据‘/’把路径拆分放进数组,然后从第一个开始比较,相同的忽略掉,直到遇到不同的为止。
<?php$a = "/a/b/c/d/test.php";$b = "/a/b/e/f/other.php";
//拆分路径放进数组:$_a = explode('/', $a);$_b = explode('/', $b);
//开始比对数组,存下不同的部分:$remain_a = array_diff($_a, $_b);$remain_b = array_diff($_b, $_a);
//$remain_a = array("c", "d", "test.php");//$remain_b = array("e", "f", "other.php") ;
//算出$a路径的剩余深度$count = count($remain_a);//算出$b剩余路径,再合并成路径形式: $b = "e/f/other.php"$relative_path_b = join('/', $remain_b);
//计算相对路径前缀for($i = 0; $i < $count-1; $i++){ $new .= '../';}$_path = $new . $relative_path_b;
//输出 ../../e/f/other.phpecho $_path;