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

A small study on the relative path method

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-07-25 09:02:371221browse
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 if($arr_a[$i]==$arr_b[$i]) {
  15. unset($arr_a[$i],$arr_b[$i]);//Remove the same part before
  16. }else{
  17. if($i==0)
  18. $flag=false;//There are no two paths Intersection
  19. break;//Stop the loop
  20. }
  21. }
  22. $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]
  23. return $str.join('/',$arr_a);//Splice and return
  24. }
  25. //TEST
  26. $a ='/a/b/c/d /e.php';
  27. $b ='/a/b/12/34/c.php';
  28. echo 'Path a:'.$a;
  29. echo '
    Path b:'. $b;
  30. echo '
    The relative path between path a and path b (use c.php to access the e.php path) is:';
  31. echo getRelativePath($a,$b);
  32. // -----OUTPUT-------------=
  33. Path a:/a/b/c/d/e.php
  34. Path b:/a/b/12/34/c .php
  35. 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