Home  >  Article  >  php教程  >  PHP面试题:写一个函数,算出两个文件的相对路径,4种方法

PHP面试题:写一个函数,算出两个文件的相对路径,4种方法

WBOY
WBOYOriginal
2016-06-06 19:36:031800browse

//在网上搜了4种答案,结果都不一样,请问哪个是对的?还是都不对,您有好的解决办法吗?求//解!!! ?php header("content-type:text/html;charset=utf-8"); $a='/a/b/c/d/e.php'; $b='/a/b/12/34/c.php'; function getRelativePath($a, $b) {///a/b/12/34/..

//在网上搜了4种答案,结果都不一样,请问哪个是对的?还是都不对,您有好的解决办法吗?求//解!!!

header("content-type:text/html;charset=utf-8");
$a='/a/b/c/d/e.php';
$b='/a/b/12/34/c.php';
  function getRelativePath($a, $b) {///a/b/12/34/../../c/d/e.php
    $returnPath = array(dirname($b));
    $arrA = explode('/', $a);
    $arrB = explode('/', $returnPath[0]);
    for ($n = 1, $len = count($arrB); $n         if ($arrA[$n] != $arrB[$n]) {
            break;
        }
    }
    if ($len - $n > 0) {
        $returnPath =array_merge($returnPath, array_fill(1, $len - $n, '..'));
    }
    
    $returnPath = array_merge($returnPath,array_slice($arrA, $n));
    return implode('/', $returnPath);
}
echo getRelativePath($a, $b);
//输出结果:/a/b/12/34/../../c/d/e.php
echo "


";

function getRelativePath1($a,$b){
    $a_url = array(dirname($a));
    $b_url = array(dirname($b));
    $a_arr = explode('/',$a_url[0]);
    $b_arr = explode('/',$b_url[0]);
    $len    = count($a_arr);
    $art1 = '';
    $art2 = '';
    for($i=1;$i        if($a_arr[$i]$b_arr[$i]){
            $art1.= '../';
            $art2.= $a_arr[$i].'/';
        }
    }
    return $art1.$art2;
}
echo getRelativePath1($a, $b);
//输出结果:../../c/d/
echo "
";


  function getpathinfo( $a, $b ) {
    $a2array    = explode('/', $a);
    $b2array    = explode('/', $b);
    $pathinfo   = '';
    for( $i = 1; $i         $pathinfo.=$a2array[$i] == $b2array[$i] ? '../' : $b2array[$i].'/';
    }
    print_R($pathinfo);
}
getpathinfo($a, $b);
//输出结果:../../12/34/
echo "
";


$path="";
$path1 = explode('/',dirname($a));
$path2 = explode('/',dirname($b));
$aLen = count($path1);
$bLen = count($path2);
$maxLen = max($aLen,$bLen);
for($i = 1; $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);

//输出结果:../../a/b/12/34/c.php
?>








Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn