The format of the---csdn is really dt-_-
<?php
/**
* Calculation path a relative path to path 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";
? >
The basic idea: first put the A,B2 path with/split the number of groups, define count = 0, starting from subscript 0 to traverse 2 arrays, if arr_a[0] = = Arr_b[0], then use Array_shift () to delete the first value of the array, at this time count+1, Continue the loop until it is not equal, at which point the array B is left with a,b parts. Subtracting count from the length of the array A is the number of paths a reached the a,b common path. Like 2 times, just use. /.. /represented, then, using/connecting array B, you can get a relative to B path
Reference:
1. Heuristic but faulty algorithm: http://istrone.com/?p=1165
2.array_pop Usage: http://www.php.net/manual/zh/function.array-pop.php
3.array_shift Usage: http://www.php.net/manual/zh/function.array-shift.php
4.array_diff (): Calculates the difference set for a 2 array
Array_intersect (): Intersection