PHP
—
入门 使用 PHP 计算两个路径的相对路径
本篇文章是对用 PHP 计算两个路径的相对路径进行了详细的分析介绍,需要的朋友参考
下
代码如下:
<html>
<body>
<?php
function
relativePath(
$aPath
,
$bPath
) {
$aArr
=
explode
('/',
$aPath
);
//explode 函数用于切分字符串,返回切分后的数组,此处用'/'切分
字符串
$bArr
=
explode
('/',
$bPath
);
$aDiffToB
=
array_diff_assoc
(
$aArr
,
$bArr
);
//array_diff_assoc()用于获取 A 数组与 B 数组之
间元素的差集,Key 和 Value 都不相同视为不同元素,此处返回在 A 数组中且与 B 数组不相
同的元素
$count
=
count
(
$aDiffToB
);
$path
= '';
for
(
$i
= 0;
$i
<
$count
- 1;
$i
++){
$path
.= '../';
}
$path
.= implode('/',
$aDiffToB
);
//implode()用于使用指定字符串连接数组元素,此处返回
用'/'连接数组元素后的字符串
return
$path
;
}
echo
relativePath('/a/b/c/d/a.php', '/a/b/1/2/b.php');
?>
</body>
</html>
页面输出
. ./. ./c/d/a.php