【发布时间】:2021-06-17 09:07:38
【问题描述】:
假设我有这两个目录路径:
"/www/website/news/old/"
"/www/library/js/"
我需要一个 PHP 函数来输出从一个目录到另一个目录的相对路径。在这个例子中,它应该输出类似 "../../../library/js/"
【问题讨论】:
假设我有这两个目录路径:
"/www/website/news/old/"
"/www/library/js/"
我需要一个 PHP 函数来输出从一个目录到另一个目录的相对路径。在这个例子中,它应该输出类似 "../../../library/js/"
【问题讨论】:
以下功能可以完成这项工作:
function getRelativePath($source, $destination) {
$sourceArray = [];
preg_match_all('/([^\/]+)/', $source, $sourceArray);
$destinationArray = [];
preg_match_all('/([^\/]+)/', $destination, $destinationArray);
$sourceArray = array_reverse($sourceArray[0]);
$destinationArray = array_reverse($destinationArray[0]);
$relative = [];
$hasPath = false;
foreach ($sourceArray as $path) {
for ($i = 0; $i < count($destinationArray); $i++ ) {
$to = $destinationArray[$i];
if ($path == $to) {
$hasPath = true;
for ($j = $i - 1; $j >= 0 ; $j--)
$relative[] = $destinationArray[$j];
break 2;
}
}
$relative[] = "..";
}
return $hasPath ? implode("/",$relative) . "/" : "NO PATH";
}
【讨论】: