【问题标题】:PHP - Get relative path from one directory to anotherPHP - 获取从一个目录到另一个目录的相对路径
【发布时间】:2021-06-17 09:07:38
【问题描述】:

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

"/www/website/news/old/"

"/www/library/js/"

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

【问题讨论】:

    标签: php directory path


    【解决方案1】:

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

    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";
    }
    

    【讨论】:

      猜你喜欢
      • 2012-01-26
      • 1970-01-01
      • 1970-01-01
      • 2011-11-06
      • 1970-01-01
      • 2011-12-16
      • 2011-11-08
      • 2012-12-26
      • 2020-10-23
      相关资源
      最近更新 更多