当前位置:Gxlcms > PHP教程 > 通过php计算两个文件之间的相对路径方法

通过php计算两个文件之间的相对路径方法

时间:2021-07-01 10:21:17 帮助过:7人阅读

php 计算两个文件之间的相对路径方法

例如:

文件A 的路径是 /home/web/lib/img/cache.php

文件B的路径是 /home/web/api/img/show.php

那么,文件A相对于文件B的路径是 ../../lib/img/cache.php,即文件B 访问 文件A的相对路径。

function getRelativePath

  1. <?php
  2. /** 计算path1 相对于 path2 的路径,即在path2引用paht1的相对路径
  3. * @param String $path1
  4. * @param String $path2
  5. * @return String
  6. */
  7. function getRelativePath($path1, $path2){
  8. $arr1 = explode('/', $path1);
  9. $arr2 = explode('/', $path2);
  10. // 获取相同路径的部分
  11. $intersection = array_intersect_assoc($arr1, $arr2);
  12. $depth = 0;
  13. for($i=0,$len=count($intersection); $i<$len; $i++){
  14. $depth = $i;
  15. if(!isset($intersection[$i])){
  16. break;
  17. }
  18. }
  19. // 前面全部匹配
  20. if($i==count($intersection)){
  21. $depth ++;
  22. }
  23. // 将path2的/ 转为 ../,path1获取后面的部分,然后合拼
  24. // 计算前缀
  25. if(count($arr2)-$depth-1>0){
  26. $prefix = array_fill(0, count($arr2)-$depth-1, '..');
  27. }else{
  28. $prefix = array('.');
  29. }
  30. $tmp = array_merge($prefix, array_slice($arr1, $depth));
  31. $relativePath = implode('/', $tmp);
  32. return $relativePath;
  33. }
  34. ?>

demo

  1. <?php
  2. $path1 = '/home/web/lib/img/cache.php';
  3. $path2 = '/home/show.php';
  4. echo getRelativePath($path1, $path2).'<br>'; // ./web/lib/img/cache.php
  5. $path1 = '/home/web/lib/img/cache.php';
  6. $path2 = '/home/web/api/show.php';
  7. echo getRelativePath($path1, $path2).'<br>'; // ../lib/img/cache.php
  8. $path1 = '/home/web/lib/img/cache.php';
  9. $path2 = '/home/web/api/img/show.php';
  10. echo getRelativePath($path1, $path2).'<br>'; // ../../lib/img/cache.php
  11. $path1 = '/home/web/lib/img/cache.php';
  12. $path2 = '/xhome/web/show.php';
  13. echo getRelativePath($path1, $path2).'<br>'; // ../../home/web/lib/img/cache.php
  14. ?>

本文讲解了通过php 计算两个文件之间的相对路径方法 ,更多相关内容请关注Gxl网。

相关推荐:

讲解php获取指定日期的相关内容

详解PHP生成唯一RequestID类

如何通过MySQL查看数据库表容量大小

以上就是通过php 计算两个文件之间的相对路径方法的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行