php 计算两个文件之间的相对路径方法
例如:
文件A 的路径是 /home/web/lib/img/cache.php
文件B的路径是 /home/web/api/img/show.php
那么,文件A相对于文件B的路径是 ../../lib/img/cache.php,即文件B 访问 文件A的相对路径。
function getRelativePath
<?php
/** 计算path1 相对于 path2 的路径,即在path2引用paht1的相对路径
* @param  String $path1
* @param  String $path2
* @return String
*/
function getRelativePath($path1, $path2){
    $arr1 = explode('/', $path1);
    $arr2 = explode('/', $path2);
    // 获取相同路径的部分
    $intersection = array_intersect_assoc($arr1, $arr2);
    $depth = 0;
    for($i=0,$len=count($intersection); $i<$len; $i++){
        $depth = $i;
        if(!isset($intersection[$i])){
            break;
        }
    }
    // 前面全部匹配
    if($i==count($intersection)){
        $depth ++;
    }
    // 将path2的/ 转为 ../,path1获取后面的部分,然后合拼
    
    // 计算前缀
    if(count($arr2)-$depth-1>0){
        $prefix = array_fill(0, count($arr2)-$depth-1, '..');
    }else{
        $prefix = array('.');
    }
    $tmp = array_merge($prefix, array_slice($arr1, $depth));
    $relativePath = implode('/', $tmp);
    return $relativePath;
}
?>demo
<?php $path1 = '/home/web/lib/img/cache.php'; $path2 = '/home/show.php'; echo getRelativePath($path1, $path2).'<br>'; // ./web/lib/img/cache.php $path1 = '/home/web/lib/img/cache.php'; $path2 = '/home/web/api/show.php'; echo getRelativePath($path1, $path2).'<br>'; // ../lib/img/cache.php $path1 = '/home/web/lib/img/cache.php'; $path2 = '/home/web/api/img/show.php'; echo getRelativePath($path1, $path2).'<br>'; // ../../lib/img/cache.php $path1 = '/home/web/lib/img/cache.php'; $path2 = '/xhome/web/show.php'; echo getRelativePath($path1, $path2).'<br>'; // ../../home/web/lib/img/cache.php ?>
本文讲解了通过php 计算两个文件之间的相对路径方法 ,更多相关内容请关注php中文网。
相关推荐:
以上就是通过php 计算两个文件之间的相对路径方法的详细内容,更多请关注php中文网其它相关文章!
                        
                        PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号