Home  >  Article  >  Backend Development  >  php计算两个文件相对路径的方法_php技巧

php计算两个文件相对路径的方法_php技巧

WBOY
WBOYOriginal
2016-05-16 20:20:56996browse

本文实例讲述了php计算两个文件相对路径的方法。分享给大家供大家参考。具体如下:

一、问题:

写一个php函数算出两个文件的相对路径。例如$a="/a/b/c/d/e.php"; $b="/a/b/12/34/c.php",B相对于A的相对路径是什么?

二、解决方法:

<&#63;php
/**
 * 求$b相对于$a的相对路径
 * @param string $a
 * @param string $b
 * @return string
 */
function getRelativePath ($a, $b)
{
  $patha = explode('/', $a);
  $pathb = explode('/', $b);
  $counta = count($patha) - 1;
  $countb = count($pathb) - 1;
  $path = "../";
  if ($countb > $counta) {
    while ($countb > $counta) {
      $path .= "../";
      $countb --;
    }
  }
  // 寻找第一个公共结点
  for ($i = $countb - 1; $i >= 0;) {
    if ($patha[$i] != $pathb[$i]) {
      $path .= "../";
      $i --;
    } else {
//判断是否为真正的第一个公共结点,防止出现子目录重名情况
      for ($j = $i - 1, $flag = 1; $j >= 0; $j --) {
        if ($patha[$j] == $pathb[$j]) {
          continue;
        } else {
          $flag = 0;
          break;
        }
      }
      if ($flag)
        break;
      else
        $i ++;
    }
  }
  for ($i += 1; $i <= $counta; $i ++) {
    $path .= $patha[$i] . "/";
  }
  return $path;
}
$a = "/a/c/d/e.php";
$b = "/a/c.php";
$path = getRelativePath($a, $b);
echo $path;

希望本文所述对大家的php程序设计有所帮助。

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