As in the title, find the relative paths of two paths, and ask for a brick!
- /**
- * Find the relative path of two paths
- * @param string $patha path a
- * @param string $pathb path b
- * @author Joychao
- * @link http://www.joychao .cc
- * @return string relative path
- */
- function getRelativePath($patha,$pathb){
- $arr_a=explode('/',trim(dirname($patha),'/'));
- $arr_b =explode('/',trim(dirname($pathb),'/'));
- $n=min(count($arr_a),count($arr_b));//Use the shortest path to loop
- $flag =true;//Mark bit [whether the mark has no intersection at all]
- for($i=0;$i<$n;$i++){
- if($arr_a[$i]==$arr_b[$i]) {
- unset($arr_a[$i],$arr_b[$i]);//Remove the same part before
- }else{
- if($i==0)
- $flag=false;//There are no two paths Intersection
- break;//Stop the loop
- }
- }
- $str=$flag?str_repeat('../',count($arr_b)+1):'/';//If there is no intersection, it is the root directory" /"[Linux situation, Windows can change it by itself]
- return $str.join('/',$arr_a);//Splice and return
- }
- //TEST
- $a ='/a/b/c/d /e.php';
- $b ='/a/b/12/34/c.php';
- echo 'Path a:'.$a;
- echo '
Path b:'. $b;
- echo '
The relative path between path a and path b (use c.php to access the e.php path) is:';
- echo getRelativePath($a,$b);
- // -----OUTPUT-------------=
- Path a:/a/b/c/d/e.php
- Path b:/a/b/12/34/c .php
- The relative path between path a and path b (use c.php to access the e.php path) is: ../../../c/d
Copy the code
|