給定兩個絕對路徑 $a 與 $b,求 $b 相對於 $a 的相對路徑。例如:
$a = '/a/b/c/d/e.php'$b = '/a/b/12/34/c.php'../../12/34/c.php<?php
/**
* 計算 $b 相對於 $a 的相對路徑
*
* @param string $a 基準路徑(目錄或檔案)
* @param string $b 目標路徑(目錄或檔案)
* @return string 相對路徑
*/
function getRelativePath(string $a, string $b): string {
// 正規化路徑分隔符
$a = str_replace('\\', '/', $a);
$b = str_replace('\\', '/', $b);
// 移除尾端分隔符
$a = rtrim($a, '/');
$b = rtrim($b, '/');
// 分割路徑段
$pathA = explode('/', $a);
$pathB = explode('/', $b);
// 找出共同前綴長度
$commonLength = 0;
$minLength = min(count($pathA), count($pathB));
for ($i = 0; $i < $minLength; $i++) {
if ($pathA[$i] === $pathB[$i]) {
$commonLength++;
} else {
break;
}
}
// 計算需要往上層的層數
$upLevels = count($pathA) - $commonLength;
// 建構相對路徑
$relative = '';
for ($i = 0; $i < $upLevels; $i++) {
$relative .= '../';
}
// 加上目標路徑剩餘段
for ($i = $commonLength; $i < count($pathB); $i++) {
$relative .= $pathB[$i] . '/';
}
// 移除尾端斜線(若為檔案路徑)
return rtrim($relative, '/');
}
// 測試
$a = '/a/c/d/e.php';
$b = '/a/c.php';
echo getRelativePath($a, $b); // 輸出: ../c.php
?>
/ 分割為陣列../ 重複向上層數次 + 目標路徑剩餘段原文提供的程式碼存在邏輯缺陷:
$i >= 0 但內部 $i-- 會導致無限迴圈\./、../、重複斜線)<?php
function getRelativePathAdvanced(string $from, string $to): string {
// 解析為絕對路徑(若為相對路徑)
$from = realpath($from) ?: $from;
$to = realpath($to) ?: $to;
// 正規化
$from = str_replace('\\', '/', $from);
$to = str_replace('\\', '/', $to);
// 如果是檔案路徑,取得目錄部分
if (!is_dir($from) && pathinfo($from, PATHINFO_EXTENSION)) {
$from = dirname($from);
}
if (!is_dir($to) && pathinfo($to, PATHINFO_EXTENSION)) {
$to = dirname($to);
}
$fromParts = explode('/', rtrim($from, '/'));
$toParts = explode('/', rtrim($to, '/'));
// 找共同前綴
$common = 0;
foreach ($fromParts as $i => $part) {
if (!isset($toParts[$i]) || $toParts[$i] !== $part) break;
$common++;
}
// 向上層
$up = count($fromParts) - $common;
$relative = str_repeat('../', $up);
// 向下層
$relative .= implode('/', array_slice($toParts, $common));
return $relative ?: '.';
}
?>
實際專案中,優先考慮使用 PHP 內建的 Symfony\Component\Filesystem\Path 或類似成熟庫:
<?php
// 使用 Symfony Filesystem 組件
use Symfony\Component\Filesystem\Path;
$relative = Path::makeRelative('/a/b/12/34/c.php', '/a/b/c/d/e.php');
// 結果: ../../12/34/c.php
// 或 Laravel helper
$relative = Str::relative('/a/b/12/34/c.php', '/a/b/c/d/e.php');
?>
計算相對路徑的核心在於找出共同祖先目錄,再由基準路徑向上回溯至共同祖先,再向下走向目標路徑。雖然可自行實作,但生產環境建議使用經過充分測試的成熟庫(如 Symfony Filesystem),避免邊界情況導致錯誤。自行實作時務必處理路徑正規化、跨平台分隔符、檔案與目錄路徑差異等細節。