PHP - 获取从一个目录到另一个目录的相对路径
PHP - Get relative path from one directory to another
假设我有这两个目录路径:
"/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";
}
假设我有这两个目录路径:
"/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";
}