在構建資源引用、模板繼承、遷移腳本時,常需計算「文件 B 相對於文件 A 的相對路徑」。本文提供一個純 PHP 實現函數 getRelativelyPath($from, $to),無外部依賴,邏輯清晰。
/ 分割為段陣列。$from 獨有段(需向上回溯)、$to 獨有段(需向下進入)。$from 末尾文件名段(因相對路徑基於目錄)。$from 獨有段數 = ../ 數量;$to 獨有段 = 目標路徑尾部。/ 連接。 '..', $fromOnly);
// 合併
$relativeParts = array_merge($fromOnly, $toOnly);
return implode('/', $relativeParts);
}
// 測試
$a = '/a/b/c/d/e.php';
$b = '/a/b/12/34/c.php';
echo getRelativelyPath($a, $b); // 輸出:../../12/34/c.php
$a = '/a/b/c/d/e.php';
$b = '/a/b/12/34/c.php';
// 邏輯:
// $fromParts = ['','a','b','c','d','e.php']
// $toParts = ['','a','b','12','34','c.php']
// $fromOnly = ['c','d','e.php'] → pop → ['c','d'] → ['..','..']
// $toOnly = ['12','34','c.php']
// 結果:../../12/34/c.php ✓
realpath() 規範化(解析符號鏈接、去除 ./..)。str_replace('\\', '/', $path)。filename(無 ./ 前綴),呼叫端自行補齊。$from === $to 返回空字符串,呼叫端視為同一文件。function getRelativePath($from, $to, $fromIsFile = true) {
if ($fromIsFile) $from = dirname($from);
// 後續邏輯同前
}
此函數無依賴、無副作用、可直接複製進工具類,解決「相對路徑手算易錯、框架助手函數不可用」的痛點。