/**
* 求相对路径
*
* $a = '/a/b/c/a.php';
* $b = '/a/b/e/b.php';
* echo self::relative_path($a, $b);
* // 将输出 ../../c/a.php
*
* @param string $a 目标路径
* @param string $b 相对路径
* @return string
*/
function relative_path($a, $b)
{
$str = '';
$a = explode('/', ltrim(str_replace('\\', '/', $a), '/'));
$b = explode('/', ltrim(str_replace('\\', '/', $b), '/'));
$intersect = array_intersect_assoc($a, $b);
if($intersect)
{
$j = -1;
$num = 0;
foreach ($intersect as $k => $v)
{
if($k-1 != $j)
{
break;
}
else
{
$str .= '..'. DIRECTORY_SEPARATOR;
}
$j = $k;
$num++;
}
$ret = array_slice($a, $num);
return $str . implode(DIRECTORY_SEPARATOR, $ret);
}
}
* 求相对路径
*
* $a = '/a/b/c/a.php';
* $b = '/a/b/e/b.php';
* echo self::relative_path($a, $b);
* // 将输出 ../../c/a.php
*
* @param string $a 目标路径
* @param string $b 相对路径
* @return string
*/
function relative_path($a, $b)
{
$str = '';
$a = explode('/', ltrim(str_replace('\\', '/', $a), '/'));
$b = explode('/', ltrim(str_replace('\\', '/', $b), '/'));
$intersect = array_intersect_assoc($a, $b);
if($intersect)
{
$j = -1;
$num = 0;
foreach ($intersect as $k => $v)
{
if($k-1 != $j)
{
break;
}
else
{
$str .= '..'. DIRECTORY_SEPARATOR;
}
$j = $k;
$num++;
}
$ret = array_slice($a, $num);
return $str . implode(DIRECTORY_SEPARATOR, $ret);
}
}
调用方法:
$a = '/a/b/c/a.php';
$b = '/a/b/e/b.php';
echo relative_path($a, $b);
// 将输出 ../../c/a.php
$b = '/a/b/e/b.php';
echo relative_path($a, $b);
// 将输出 ../../c/a.php