Heim  >  Artikel  >  Backend-Entwicklung  >  求相对路径方法小研究

求相对路径方法小研究

WBOY
WBOYOriginal
2016-07-25 09:02:371121Durchsuche
如题,求两路径相对路径,求拍砖!
  1. /**
  2. * 求两路径的相对路径
  3. * @param string $patha 路径a
  4. * @param string $pathb 路径b
  5. * @author Joychao
  6. * @link http://www.joychao.cc
  7. * @return string 相对路径
  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));//用最短路径来循环
  13. $flag=true;//标记位[标记是否完全没有交集]
  14. for($i=0;$i if($arr_a[$i]==$arr_b[$i]){
  15. unset($arr_a[$i],$arr_b[$i]);//去除前面相同的部分
  16. }else{
  17. if($i==0)
  18. $flag=false;//两路径没有交集
  19. break;//停止循环
  20. }
  21. }
  22. $str=$flag?str_repeat('../',count($arr_b)+1):'/';//没有交集则为根目录"/"[Linux情况,windows自己改]
  23. return $str.join('/',$arr_a);//拼接并返回
  24. }
  25. //TEST
  26. $a ='/a/b/c/d/e.php';
  27. $b ='/a/b/12/34/c.php';
  28. echo '路径a:'.$a;
  29. echo '
    路径b:'.$b;
  30. echo '
    路径a和路径b的相对路径(用c.php去访问e.php路径)为:';
  31. echo getRelativePath($a,$b);
  32. //-----OUTPUT-------------=
  33. 路径a:/a/b/c/d/e.php
  34. 路径b:/a/b/12/34/c.php
  35. 路径a和路径b的相对路径(用c.php去访问e.php路径)为:../../../c/d
复制代码


Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn