Home  >  Article  >  Backend Development  >  A small study on the relative path method

A small study on the relative path method

WBOY
WBOYOriginal
2016-07-25 09:02:371158browse
As in the title, find the relative paths of two paths, and ask for a brick!
  1. /**
  2. * Find the relative path of two paths
  3. * @param string $patha path a
  4. * @param string $pathb path b
  5. * @author Joychao
  6. * @link http://www.joychao .cc
  7. * @return string relative path
  8. */
  9. function getRelativePath($patha,$pathb){
  10. $arr_a=explode('/',trim(dirname($patha),'/'));
  11. $arr_b =explode('/',trim(dirname($pathb),'/'));
  12. $n=min(count($arr_a),count($arr_b));//Use the shortest path to loop
  13. $flag =true;//Mark bit [whether the mark has no intersection at all]
  14. for($i=0;$i<$n;$i++){
  15. if($arr_a[$i]==$arr_b[$i]) {
  16. unset($arr_a[$i],$arr_b[$i]);//Remove the same part before
  17. }else{
  18. if($i==0)
  19. $flag=false;//There are no two paths Intersection
  20. break;//Stop the loop
  21. }
  22. }
  23. $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]
  24. return $str.join('/',$arr_a);//Splice and return
  25. }
  26. //TEST
  27. $a ='/a/b/c/d /e.php';
  28. $b ='/a/b/12/34/c.php';
  29. echo 'Path a:'.$a;
  30. echo '
    Path b:'. $b;
  31. echo '
    The relative path between path a and path b (use c.php to access the e.php path) is:';
  32. echo getRelativePath($a,$b);
  33. // -----OUTPUT-------------=
  34. Path a:/a/b/c/d/e.php
  35. Path b:/a/b/12/34/c .php
  36. The relative path between path a and path b (use c.php to access the e.php path) is: ../../../c/d
Copy the code


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn