首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 計算兩檔案相對路徑

     編輯:PHP 綜合知識

需求:給定兩個絕對路徑 $a、$b,求 $b 相對於 $a 的相對路徑。例:/a/b/c/d/e.php 對 /a/b/12/34/c.php → ../../12/34/c.php。

演算法步驟

  1. 以 / 分割路徑為陣列
  2. 找出最長共同前綴(共同祖先目錄)
  3. 計算從 $a 到共同祖先需幾個 ../
  4. 接上從共同祖先到 $b 的剩餘路徑

完整函數

function getRelativePath($from, $to) {
    $from = rtrim($from, '/');
    $to   = rtrim($to, '/');
    $fromParts = explode('/', $from);
    $toParts   = explode('/', $to);
    // 找共同前綴長度
    $common = 0;
    $minLen = min(count($fromParts), count($toParts));
    for ($i = 0; $i < $minLen; $i++) {
        if ($fromParts[$i] === $toParts[$i]) $common++;
        else break;
    }
    // 建構相對路徑
    $up = count($fromParts) - $common;
    $rel = str_repeat('../', $up);
    $rel .= implode('/', array_slice($toParts, $common));
    return $rel;
}

// 測試
echo getRelativePath('/a/b/c/d/e.php', '/a/b/12/34/c.php'); // ../../12/34/c.php
echo getRelativePath('/var/www/a.php', '/var/www/b/c.php'); // b/c.php
echo getRelativePath('/a/b/c', '/x/y/z'); // ../../../x/y/z

注意事項

  • 輸入路徑建議先 realpath() 正規化(解析符號連結、..、.)
  • Windows 路徑分隔符 \ 需統一轉 / 或用 DIRECTORY_SEPARATOR
  • 若在不同磁碟機 (Windows) 無相對路徑,需回傳絕對路徑

現代替代:Symfony String / League URI

use Symfony\Component\String\UnicodeString;
$rel = (new UnicodeString($to))->getRelativePath($from);

掌握核心演算法,或直接用成熟元件避免邊界錯誤。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved