zoukankan      html  css  js  c++  java
  • php 两个文件之间的相对路径的计算方法

    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++){
            if(!isset($intersection[$i])){
                $depth = $i;
                break;
            }
        }
    
        // 将path2的/ 转为 ../,path1获取后面的部分。然后合拼
        $tmp = array_merge(array_fill(0, count($arr2)-$depth-1, '..'), array_slice($arr1, $depth));
    
        $relativePath = implode('/', $tmp);
    
        return $relativePath;
    }
    ?>

    demo

    <?php
    $path1 = '/home/web/lib/img/cache.php';
    $path2 = '/home/web/api/img/show.php';
    
    echo getRelativePath($path1, $path2); // ../../lib/img/cache.php
    ?

    >





    版权声明:本文博主原创文章,博客,未经同意不得转载。

  • 相关阅读:
    5.9
    5.8
    5.4
    04--深入探讨C++中的引用
    01--Qt扫盲篇
    00--Qt Creator 你必须要掌握的快捷操作
    02--读书笔记之:C++ Primer (第4版)及习题
    01--[转]C++强大背后
    01--数据结构——动态链表(C++)
    04-手把手教你把Vim改装成一个IDE编程环境(图文)
  • 原文地址:https://www.cnblogs.com/lcchuguo/p/4870821.html
Copyright © 2011-2022 走看看