当我输入标题时,我注意到有关此问题的一些类似问题,但它们似乎不是在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'
有什么好主意吗?感谢。
答案 0 :(得分:63)
试试这个:
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
答案 1 :(得分:14)
由于我们有几个答案,我决定对它们进行测试并对它们进行基准测试。 我用这条路来测试:
$from = "/var/www/sites/web/mainroot/webapp/folder/sub/subf/subfo/subfol/subfold/lastfolder/";
注意:如果是文件夹,则必须为函数设置一个尾部斜杠才能正常工作!因此,__DIR__
将不起作用。请改为使用__FILE__
或__DIR__ . '/'
$to = "/var/www/sites/web/mainroot/webapp/folder/aaa/bbb/ccc/ddd";
结果:(小数点分隔符为逗号,千位分隔符为点)
所以,我建议您使用Gordon的实施! (标记为答案的那个)
Young的一个也很好,并且使用简单的目录结构(例如" a / b / c.php")表现更好,而Gordon的一个表现更好,复杂的结构,有很多子目录(比如这个基准测试中使用的子目录)。
注意:我在下面写下了以$from
和$to
作为输入返回的结果,因此您可以验证其中2个是正常的,而其他2个是错误的:
../../../../../../aaa/bbb/ccc/ddd
- > CORRECT ../../../../../../aaa/bbb/ccc/ddd
- > CORRECT ../../../../../../bbb/ccc/ddd
- > WRONG ../../../../../aaa/bbb/ccc/ddd
- > WRONG 答案 2 :(得分:8)
相对路径?这似乎更像是一条旅行路径。您似乎想知道从路径A到路径B的路径。如果是这种情况,您可以在'/'
上explode $ a和$ b然后反向遍历$ aParts,将它们与同一索引的$ bPart进行比较,直到找到“common denominator”目录(记录沿途的循环次数)。然后创建一个空字符串并将'../'
添加到$ numLoops-1次,然后添加到$ b减去公分母目录。
答案 3 :(得分:4)
const DS = DIRECTORY_SEPARATOR; // for convenience
function getRelativePath($from, $to) {
$dir = explode(DS, is_file($from) ? dirname($from) : rtrim($from, DS));
$file = explode(DS, $to);
while ($dir && $file && ($dir[0] == $file[0])) {
array_shift($dir);
array_shift($file);
}
return str_repeat('..'.DS, count($dir)) . implode(DS, $file);
}
我的尝试是故意更简单的,尽管表现可能没有什么不同。我将基准测试作为好奇读者的练习。但是,这非常强大,应该与平台无关。
谨防使用array_intersect
函数的解决方案,如果并行目录具有相同的名称,这些函数将会中断。例如,getRelativePath('start/A/end/', 'start/B/end/')
会返回“../end
”,因为array_intersect
会找到所有相同的名称,在这种情况下为2时应该只有1。
答案 4 :(得分:2)
根据Gordon的功能,我的解决方案如下:
function getRelativePath($from, $to)
{
$from = explode('/', $from);
$to = explode('/', $to);
foreach($from as $depth => $dir)
{
if(isset($to[$depth]))
{
if($dir === $to[$depth])
{
unset($to[$depth]);
unset($from[$depth]);
}
else
{
break;
}
}
}
//$rawresult = implode('/', $to);
for($i=0;$i<count($from)-1;$i++)
{
array_unshift($to,'..');
}
$result = implode('/', $to);
return $result;
}
答案 5 :(得分:2)
此代码取自Symfony URL生成器 https://github.com/symfony/Routing/blob/master/Generator/UrlGenerator.php
/**
* Returns the target path as relative reference from the base path.
*
* Only the URIs path component (no schema, host etc.) is relevant and must be given, starting with a slash.
* Both paths must be absolute and not contain relative parts.
* Relative URLs from one resource to another are useful when generating self-contained downloadable document archives.
* Furthermore, they can be used to reduce the link size in documents.
*
* Example target paths, given a base path of "/a/b/c/d":
* - "/a/b/c/d" -> ""
* - "/a/b/c/" -> "./"
* - "/a/b/" -> "../"
* - "/a/b/c/other" -> "other"
* - "/a/x/y" -> "../../x/y"
*
* @param string $basePath The base path
* @param string $targetPath The target path
*
* @return string The relative target path
*/
function getRelativePath($basePath, $targetPath)
{
if ($basePath === $targetPath) {
return '';
}
$sourceDirs = explode('/', isset($basePath[0]) && '/' === $basePath[0] ? substr($basePath, 1) : $basePath);
$targetDirs = explode('/', isset($targetPath[0]) && '/' === $targetPath[0] ? substr($targetPath, 1) : $targetPath);
array_pop($sourceDirs);
$targetFile = array_pop($targetDirs);
foreach ($sourceDirs as $i => $dir) {
if (isset($targetDirs[$i]) && $dir === $targetDirs[$i]) {
unset($sourceDirs[$i], $targetDirs[$i]);
} else {
break;
}
}
$targetDirs[] = $targetFile;
$path = str_repeat('../', count($sourceDirs)).implode('/', $targetDirs);
// A reference to the same base directory or an empty subdirectory must be prefixed with "./".
// This also applies to a segment with a colon character (e.g., "file:colon") that cannot be used
// as the first segment of a relative-path reference, as it would be mistaken for a scheme name
// (see http://tools.ietf.org/html/rfc3986#section-4.2).
return '' === $path || '/' === $path[0]
|| false !== ($colonPos = strpos($path, ':')) && ($colonPos < ($slashPos = strpos($path, '/')) || false === $slashPos)
? "./$path" : $path;
}
答案 6 :(得分:1)
戈登的某些原因对我不起作用......这是我的解决方案
function getRelativePath($from, $to) {
$patha = explode('/', $from);
$pathb = explode('/', $to);
$start_point = count(array_intersect($patha,$pathb));
while($start_point--) {
array_shift($patha);
array_shift($pathb);
}
$output = "";
if(($back_count = count($patha))) {
while($back_count--) {
$output .= "../";
}
} else {
$output .= './';
}
return $output . implode('/', $pathb);
}
答案 7 :(得分:1)
我使用这些数组操作得到了相同的结果:
function getRelativePath($path, $from = __FILE__ )
{
$path = explode(DIRECTORY_SEPARATOR, $path);
$from = explode(DIRECTORY_SEPARATOR, dirname($from.'.'));
$common = array_intersect_assoc($path, $from);
$base = array('.');
if ( $pre_fill = count( array_diff_assoc($from, $common) ) ) {
$base = array_fill(0, $pre_fill, '..');
}
$path = array_merge( $base, array_diff_assoc($path, $common) );
return implode(DIRECTORY_SEPARATOR, $path);
}
第二个参数是路径相对的文件。它是可选的,因此无论您当前的网页是什么,您都可以获得相对路径。 为了与@Young或@Gordon示例一起使用,因为你想知道$ a的$ b的相对路径,你将不得不使用
getRelativePath($b, $a);
答案 8 :(得分:0)
简单的单线程用于常见场景:
str_replace(getcwd() . DIRECTORY_SEPARATOR, '', $filepath)
或:
substr($filepath, strlen(getcwd())+1)
要检查路径是否绝对,请尝试:
$filepath[0] == DIRECTORY_SEPARATOR
答案 9 :(得分:0)
这对我有用。由于某些未知原因,对此问题的最热烈回答没有按预期工作
public function getRelativePath($absolutePathFrom, $absolutePathDestination)
{
$absolutePathFrom = is_dir($absolutePathFrom) ? rtrim($absolutePathFrom, "\/")."/" : $absolutePathFrom;
$absolutePathDestination = is_dir($absolutePathDestination) ? rtrim($absolutePathDestination, "\/")."/" : $absolutePathDestination;
$absolutePathFrom = explode("/", str_replace("\\", "/", $absolutePathFrom));
$absolutePathDestination = explode("/", str_replace("\\", "/", $absolutePathDestination));
$relativePath = "";
$path = array();
$_key = 0;
foreach($absolutePathFrom as $key => $value)
{
if (strtolower($value) != strtolower($absolutePathDestination[$key]))
{
$_key = $key + 1;
for ($i = $key; $i < count($absolutePathDestination); $i++)
{
$path[] = $absolutePathDestination[$i];
}
break;
}
}
for ($i = 0; $i <= (count($absolutePathFrom) - $_key - 1); $i++)
{
$relativePath .= "../";
}
return $relativePath.implode("/", $path);
}
如果$a = "C:\xampp\htdocs\projects\SMS\App\www\App\index.php"
和
$b = "C:\xampp\htdocs\projects\SMS\App/www/App/bin/bootstrap/css/bootstrap.min.css"
然后$c
,$b
的{{1}}的相对路径将是
$a