php 获取相对路径实例代码
- function getRelativePath($a, $b) {
- $returnPath = array(dirname($b));
- $arrA = explode('/', $a);
- $arrB = explode('/', $returnPath[0]);
- for ($n = 1, $len = count($arrB); $n < $len; $n++) {
- if ($arrA[$n] != $arrB[$n]) {
- break;
- }
- }
- if ($len - $n > 0) {
- $returnPath = array_merge($returnPath, array_fill(1, $len - $n, '..'));
- }
-
- $returnPath = array_merge($returnPath, array_slice($arrA, $n));
- return implode('/', $returnPath);
- }
- var_dump(getRelativePath($a, $b));
-
- $a = "/a/b/c/d/index.php";
-
-
- $b = "/a/b/12/34/index2.php";
- function getRelativePath($path1,$path2){
- $p1 = dirname($path1);
- $p2 = dirname($path2);
- $arr1 = explode('/',$p1);
- $arr2 = explode('/',$p2);
- $diff_arr= array_diff($arr2,$arr1);
- $inter_arr = array_intersect($arr1,$arr2);
-
- $leng = count($inter_arr);
- for($i=1;$i<$leng;$i++){
- $inter_arr[$i] = '..';
- }
-
- $merge_arr = array_merge($inter_arr,$diff_arr);
- $fina_arr = implode('/',$merge_arr);
- return $fina_arr;
- }
- var_dump(getRelativePath($a,$b));
-
-
|