从PHP中的绝对路径获取相对路径

键入标题时,我注意到有关此问题的一些类似问题,但它们似乎不在PHP中。那么用PHP函数解决该问题的方法是什么?

待指定。

$a="/home/apache/a/a.php";

$b="/home/root/b/b.php";

$relpath = getRelativePath($a,$b); //needed function,should return '../../root/b/b.php'

有什么好主意吗?谢谢。

回答:

试试这个:

function getRelativePath($from, $to)

{

// some compatibility fixes for Windows paths

$from = is_dir($from) ? rtrim($from, '\/') . '/' : $from;

$to = is_dir($to) ? rtrim($to, '\/') . '/' : $to;

$from = str_replace('\\', '/', $from);

$to = str_replace('\\', '/', $to);

$from = explode('/', $from);

$to = explode('/', $to);

$relPath = $to;

foreach($from as $depth => $dir) {

// find first non-matching dir

if($dir === $to[$depth]) {

// ignore this directory

array_shift($relPath);

} else {

// get number of remaining dirs to $from

$remaining = count($from) - $depth;

if($remaining > 1) {

// add traversals up to first matching dir

$padLength = (count($relPath) + $remaining - 1) * -1;

$relPath = array_pad($relPath, $padLength, '..');

break;

} else {

$relPath[0] = './' . $relPath[0];

}

}

}

return implode('/', $relPath);

}

这将给

$a="/home/a.php";

$b="/home/root/b/b.php";

echo getRelativePath($a,$b), PHP_EOL; // ./root/b/b.php

$a="/home/apache/a/a.php";

$b="/home/root/b/b.php";

echo getRelativePath($a,$b), PHP_EOL; // ../../root/b/b.php

$a="/home/root/a/a.php";

$b="/home/apache/htdocs/b/en/b.php";

echo getRelativePath($a,$b), PHP_EOL; // ../../apache/htdocs/b/en/b.php

$a="/home/apache/htdocs/b/en/b.php";

$b="/home/root/a/a.php";

echo getRelativePath($a,$b), PHP_EOL; // ../../../../root/a/a.php

以上是 从PHP中的绝对路径获取相对路径 的全部内容, 来源链接: utcz.com/qa/417876.html

回到顶部