假设我有这两个目录路径:
“/www/网站/新闻/旧/”
“/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";
}
这是一个简单的函数,假设源和目标都存在:
function getRelativePath($source, $destination)
{
$paths =
array_map(fn ($arg) => explode('/', realpath($arg)), func_get_args());
return
str_repeat('../', count(array_diff_assoc(...$paths))) .
implode('/', array_diff_assoc(...array_reverse($paths)));
}
没什么特别的。不会对源是文件夹而不是文件进行检查(请注意,目标可以是文件,而源应该是计算相对路径的目录。