回覆列表
  • 1 # 使用者1844319796352

    php 計算兩個檔案之間的相對路徑方法

    例如:

    檔案A 的路徑是 /home/web/lib/img/cache.php

    檔案B的路徑是 /home/web/api/img/show.php

    那麼,檔案A相對於檔案B的路徑是 ../../lib/img/cache.php,即檔案B 訪問 檔案A的相對路徑。

    function getRelativePath

    [php] view plain copy

    /** 計算path1 相對於 path2 的路徑,即在path2引用paht1的相對路徑

    * @param String $path1

    * @param String $path2

    * @return String

    */

    function getRelativePath($path1, $path2){

    $arr1 = explode("/", $path1);

    $arr2 = explode("/", $path2);

    // 獲取相同路徑的部分

    $intersection = array_intersect_assoc($arr1, $arr2);

    $depth = 0;

    for($i=0,$len=count($intersection); $i

    if(!isset($intersection[$i])){

    $depth = $i;

    break;

    }

    }

    // 將path2的/ 轉為 ../,path1獲取後面的部分,然後合拼

    $tmp = array_merge(array_fill(0, count($arr2)-$depth-1, ".."), array_slice($arr1, $depth));

    $relativePath = implode("/", $tmp);

    return $relativePath;

    }

  • 中秋節和大豐收的關聯?
  • 如果穿越到秦時明月,你想成為誰?