PHP - 获取从一个目录到另一个目录的相对路径

问题描述 投票:0回答:2

假设我有这两个目录路径:

“/www/网站/新闻/旧/”

“/www/library/js/”

我需要一个 PHP 函数来输出从一个目录到另一个目录的相对路径。在此示例中,它应该输出类似 "../../../library/js/"

php directory path
2个回答
2
投票

以下功能可以完成这项工作:

function getRelativePath($source, $destination) {
    $sourceArray = [];
    preg_match_all('/([^\/]+)/', $source, $sourceArray);
    $destinationArray = [];
    preg_match_all('/([^\/]+)/', $destination, $destinationArray);
    
    $sourceArray = array_reverse($sourceArray[0]);
    $destinationArray = array_reverse($destinationArray[0]);
    
    $relative = [];
    $hasPath = false;
    foreach ($sourceArray as $path) {
        for ($i = 0; $i < count($destinationArray); $i++ ) {
            $to = $destinationArray[$i];
            if ($path == $to) {
                $hasPath = true;
                for ($j = $i - 1; $j >= 0 ; $j--)
                    $relative[] = $destinationArray[$j];
                break 2;    
            }
        }
        $relative[] = "..";
    }
    return $hasPath ? implode("/",$relative) . "/" : "NO PATH";
}

0
投票

这是一个简单的函数,假设源和目标都存在:

function getRelativePath($source, $destination)
{
    $paths =
        array_map(fn ($arg) => explode('/', realpath($arg)), func_get_args());
    return
        str_repeat('../', count(array_diff_assoc(...$paths))) .
        implode('/', array_diff_assoc(...array_reverse($paths)));
}

没什么特别的。不会对源是文件夹而不是文件进行检查(请注意,目标可以是文件,而源应该是计算相对路径的目录。

© www.soinside.com 2019 - 2024. All rights reserved.