php 下面的代码是什么意思

写一个函数,算出两个文件的相对路径,如:

$a = ‘/a/b/c/d/e.php’;
$b =’/a/b/12/34/c.php’;

<?php
$a = '/a/b/c/d/e.php';   
$b ='/a/b/12/34/c.php';
$path1 = explode('/',dirname($a));
$path2 = explode('/',dirname($b));
$aLen = count($path1);
$bLen = count($path2);
$maxLen = max($aLen,$bLen);
for($i = 1; $i < $maxLen; $i++){
if($path1[$i] != $path2[$i] && isset($path1[$i])){
if(isset($path2[$i]))$bUrl[]=$path2[$i];
$path .= "../";
}else{
$bUrl[]=$path2[$i];
}
}
echo $path.implode('/',$bUrl).'/'.basename($b);
?>

不知道你具体想问什么。我帮你解释一下这个算法吧,我看你以前问过很多问题了,相信单独每句话都应该能明白。


这段代码是求文件b相对于文件a的路径,basename($b)是用来获得文件的文件名的,dirname($b)是用来获取文件所在路径的。

算法中先获取两个文件的路径,切割为数组之后已目录较深的那个数组为基准比较数组中的每一个元素,然后根据比较结果添加../或者目录名。最后获得一个相对路径。


从if($path1[$i] != $path2[$i] && isset($path1[$i])){ 这行就看出代码质量很差,不做过多说明了。

&&两边的表达式顺序不对,这是很菜鸟的错误。


我提供给你一个吧,不过这个是计算两个目录之间的相对路径的,如果需要计算文件间的相对路径你可以模仿你提供的那个代码用dirname和basename做个附加处理就行了。

/**
 * Calculate relative path
 * @param string $basePath
 * @param string $targetPath
 * @return string
 */
function CalculateRelativePath($basePath, $targetPath) {
$basePath = rtrim(str_replace('\\', '/', $basePath), '/');
$targetPath = rtrim(str_replace('\\', '/', $targetPath), '/');
$_targetPath = $targetPath;
if ($basePath == $targetPath) {
return '.';
}
$basePath = explode('/', $basePath);
$targetPath = explode('/', $targetPath);
$length = count($basePath);
if (count($targetPath) > $length) {
$length = count($targetPath);
}
$basePath[0] = strtoupper($basePath[0]);
$targetPath[0] = strtoupper($targetPath[0]);
if ($basePath[0] != $targetPath[0]) {
return $_targetPath;
}
$relativePath = '';
$i = 0;
for(; $i < $length; $i ++) {
if (! isset($basePath[$i])) {
$base = false;
} else {
$base = $basePath[$i];
}
if (! isset($targetPath[$i])) {
$target = false;
} else {
$target = $targetPath[$i];
}
/* Ignore case if windows */
if (! empty($basePath[0])) {
$target = strtoupper($target);
$base = strtoupper($base);
}
if ($base !== $target) {
break;
}
}
$length = count($basePath);
for ($j = $i; $j < $length; $j ++) {
$relativePath .= '../';
}
$length = count($targetPath);
for ($j = $i; $j < count($targetPath); $j ++) {
$relativePath .= $targetPath[$j] . '/';
}
$relativePath = rtrim($relativePath, '/');
if (empty($relativePath)) {
$relativePath = '.';
}
return $relativePath;
}


如果对你有帮助的话,希望你能把题目修改为:如何使用PHP计算两个目录之间的相对路径,这样我就能拿去申请优质回答咯,非常感谢。

追问

。。。。貌似改不了题目

追答

哦,改不了就算了,呵呵

温馨提示:答案为网友推荐,仅供参考

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网