---CSDN的这个格式实在DT-_-
<?php
/**
* 计算路径a对于路径b的相对路径
* @author wusuopubupt
* @date 2013-08-01
* */
$dira = '/a/e.php';
$dirb = '/a/b/f/e/g.php';
//explode directions
$arr_dira = explode('/', $dira);
$arr_dirb = explode('/', $dirb);
$count_a = count($arr_dira);
$count_b = count($arr_dirb);
$max = max($count_a,$count_b);
$count =0;
for ($i = 0 ; $i<$max ; $i++) {
if(isset($arr_dira[0]) && isset($arr_dirb[0]) && $arr_dira[0] == $arr_dirb[0]){
array_shift($arr_dira);
array_shift($arr_dirb);
$count ++;
}
}
$relative_path = str_repeat('../', $count_a - $count);
echo $relative_path . implode('/', $arr_dirb) . "\n";
?>
基本思路:先把a,b2个路径用/分割成数组,定义count = 0;从下标为0开始遍历2个数组,如果arr_a[0] == arr_b[0],那就用array_shift()删除数组第一个值,此时count+1,继续循环直到不相等,此时数组b只剩下a,b不相同的部分。用数组a的长度减去count,就是路径a 到达a,b共同路径的次数。比如2次,就用../../表示,然后,用/连接数组b,即可得到a相对于b的路径
参考:
1.启发的但是有错误的算法: http://istrone.com/?p=1165
2.array_pop 用法: http://www.php.net/manual/zh/function.array-pop.php
3.array_shift用法:http://www.php.net/manual/zh/function.array-shift.php
4.array_diff():计算2个数组的差集
array_intersect():交集