Home >Backend Development >PHP Tutorial >php代码实现 两个目录之间的相对路径

php代码实现 两个目录之间的相对路径

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-06-23 13:36:17884browse

/** * 获取两个路径之间的相对路径 * @param $path1  路径1 * @param $path2  路径2 * @return 返回相对路径或者false(在同一个目录下) */function relativePath($path1, $path2){    // 将各自的路径(不包含文件)存放到array数组中    $arr1 = explode('/', dirname($path1));    $arr2 = explode('/', dirname($path2));    // 遍历数组    $len = count($arr2);    for ($i = 0; $i < $len; $i++) {        if ($arr1[$i] != $arr2[$i]) {            break;        }    }    if ($i < $len) {        // 不是相同的目录,返回相对路径        $return = array_fill(0, $len - $i, ".."); // 用'..'去填充相同的$len-$i个路径        $relativePath = array_merge($return, array_slice($arr1, $i));  // 取出$i开始的不同的路径        return implode('/', $relativePath);  // 数组变成字符串返回    } else {        // 相同的目录,直接返回false        return false;    }}dirname():去掉路径中的文件,只留目录array_fill():array_merge():array_slice():











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