Heim  >  Artikel  >  Backend-Entwicklung  >  php 计算两个文件的相对路径的实现代码

php 计算两个文件的相对路径的实现代码

WBOY
WBOYOriginal
2016-07-25 08:57:01999Durchsuche
如何计算两个文件之间的相对路径呢?用php实现是很简单的,这里分享一段代码,可以计算两个文件的相对路径,有需要的朋友不妨参考下。

计算出两个文件的相对路径。 例如,有文件如下: $a="/a/b/c/d/e.php"; $b="/a/b/12/34/c.php"。 那么如何计算出B相对于A的相对路径呢?

代码:

<?php
 /**
 * 求$b相对于$a的相对路径
 * @param string $a
 * @param string $b
 * @return string
 * @site bbs.it-home.org
 */
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;
?>


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