在建構檔案管理系統、模板引擎、靜態站點生成器時,常需計算「從路徑 A 到路徑 B 的相對路徑」。本文提供不限制目錄深度、跨平台相容的 PHP 實作,並解析核心演算法邏輯。
<?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.css | assets/css/style.css | 同層級下的子目錄 |
| C:\www\project\module\view.phtml | C:\www\project\public\js\app.js | ../../public/js/app.js | Windows 路徑自動正規化 |
| /app/Http/Controllers/Auth | /app/Models/User.php | ../../Models/User.php | Laravel 專案結構範例 |
| /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.txt | file2.txt | 同目錄下檔案 |
<?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);
}