PHP 计算两个文件的相对路径

答案

  1. /**
  2. * 找出path1相对于path2的路径
  3. */
  4. function getRelativePath($path1, $path2)
  5. {
  6. $path1Arr = explode("/", $path1);
  7. $path2Arr = explode("/", $path2);
  8. $disMatch = 0;
  9. for ($i = 0; $i < count($path1Arr); $i++) {
  10. if ($path1Arr[$i] != $path2Arr[$i]) {
  11. $disMatch = count($path1Arr) - $i;
  12. $left = array_slice($path1Arr, $i);
  13. break;
  14. }
  15. }
  16. return str_repeat("../", $disMatch) . implode("/", $left);
  17. }

测试代码:

  1. $a = '/a/b/c/d/e.php';
  2. $b = '/a/b/12/34/5.php';
  3. echo getRelativePath($a, $b);
  4. // 结果:../../../c/d/e.php