萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 計算兩個路徑之間的相對路徑:不限層級深度的通用演算法

在建構檔案管理系統、模板引擎、靜態站點生成器時,常需計算「從路徑 A 到路徑 B 的相對路徑」。本文提供不限制目錄深度、跨平台相容的 PHP 實作,並解析核心演算法邏輯。

核心函式:getRelativePath($from, $to)

<?php
/**
 * 計算 $to 相對於 $from 的相對路徑
 * @param string $from 來源路徑 (檔案或目錄)
 * @param string $to   目標路徑 (檔案或目錄)
 * @return string 相對路徑 (如: ../../target/file.txt)
 */
function getRelativePath(string $from, string $to): string
{
    // 統一路徑分隔符為 /
    $from = str_replace('\\', '/', $from);
    $to   = str_replace('\\', '/', $to);

    // 取得目錄部分 (若為檔案路徑)
    $fromDir = dirname($from);
    $toDir   = dirname($to);

    // 分割路徑片段
    $fromParts = array_filter(explode('/', $fromDir), 'strlen');
    $toParts   = array_filter(explode('/', $toDir), 'strlen');

    // 尋找共同祖先目錄深度
    $commonDepth = 0;
    $minLen = min(count($fromParts), count($toParts));
    for ($i = 0; $i < $minLen; $i++) {
        if (strcasecmp($fromParts[$i], $toParts[$i]) === 0) {
            $commonDepth++;
        } else {
            break;
        }
    }

    // 建構相對路徑:向上層級數 + 目標下層路徑
    $upLevels = count($fromParts) - $commonDepth;
    $relative = str_repeat('../', $upLevels);
    $relative .= implode('/', array_slice($toParts, $commonDepth));

    // 若 $to 是檔案,附加檔名
    if (basename($to) !== basename($toDir)) {
        $relative .= '/' . basename($to);
    }

    // 處理同目錄情況
    if ($relative === '') $relative = '.';
    if ($relative === './') $relative = '.';

    return $relative;
}

測試案例與輸出

$from$to結果說明
/home/user/project/src/Controller.php/home/user/project/config/app.php../../config/app.php向上兩層再進入 config
/var/www/html/index.php/var/www/html/assets/css/style.cssassets/css/style.css同層級下的子目錄
C:\www\project\module\view.phtmlC:\www\project\public\js\app.js../../public/js/app.jsWindows 路徑自動正規化
/app/Http/Controllers/Auth/app/Models/User.php../../Models/User.phpLaravel 專案結構範例
/a/b/c/d/e/file.txt/a/b/x/y/z/target.txt../../../x/y/z/target.txt深層嵌套跨分支
/same/dir/file1.txt/same/dir/file2.txtfile2.txt同目錄下檔案

進階版:支援 URL 與 Stream Wrapper

<?php
function getRelativePathAdvanced($from, $to, $options = [])
{
    $defaults = [
        'case_sensitive' => false,     // 路徑比較是否區分大小寫
        'resolve_symlinks' => true,    // 解析符號連結
        'url_mode' => false,           // 是否為 URL 模式 (保留 query/fragment)
    ];
    $opts = array_merge($defaults, $options);

    // URL 模式處理
    if ($opts['url_mode']) {
        $fromParsed = parse_url($from);
        $toParsed   = parse_url($to);
        if ($fromParsed['host'] !== ($toParsed['host'] ?? '')) {
            return $to; // 跨域直接返回絕對 URL
        }
        $from = $fromParsed['path'] ?? '/';
        $to   = $toParsed['path'] ?? '/';
    }

    // 解析符號連結
    if ($opts['resolve_symlinks']) {
        $from = realpath($from) ?: $from;
        $to   = realpath($to) ?: $to;
    }

    return getRelativePath($from, $to);
}

常見應用場景

  • 模板引擎:``
  • 靜態站點生成器:生成離線可瀏覽的相對連結
  • 檔案管理器:顯示「複製相對路徑」功能
  • PHP 專案自動載入:計算類別檔案相對於 vendor/autoload.php 的路徑
  • 遷移/部署腳本:驗證符號連結目標路徑正確性

效能優化建議

  • 高頻呼叫時快取 `realpath()` 結果
  • 大量路徑運算考慮使用 Symfony Filesystem 或 Flysystem 成熟庫
  • 避免在迴圈中重複 `explode`/`implode`,可預先分割路徑片段
copyright © 萬盛學電腦網 all rights reserved