Rumah  >  Artikel  >  pembangunan bahagian belakang  >  通过php 计算两个文件之间的相对路径方法

通过php 计算两个文件之间的相对路径方法

jacklove
jackloveasal
2018-06-09 11:57:572196semak imbas

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(&#39;/&#39;, $path1);
    $arr2 = explode(&#39;/&#39;, $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, &#39;..&#39;);
    }else{
        $prefix = array(&#39;.&#39;);
    }
    $tmp = array_merge($prefix, array_slice($arr1, $depth));
    $relativePath = implode(&#39;/&#39;, $tmp);
    return $relativePath;
}
?>

demo

<?php
$path1 = &#39;/home/web/lib/img/cache.php&#39;;
$path2 = &#39;/home/show.php&#39;;
echo getRelativePath($path1, $path2).&#39;<br>&#39;; // ./web/lib/img/cache.php
$path1 = &#39;/home/web/lib/img/cache.php&#39;;
$path2 = &#39;/home/web/api/show.php&#39;;
echo getRelativePath($path1, $path2).&#39;<br>&#39;; // ../lib/img/cache.php
$path1 = &#39;/home/web/lib/img/cache.php&#39;;  
$path2 = &#39;/home/web/api/img/show.php&#39;;  
echo getRelativePath($path1, $path2).&#39;<br>&#39;; // ../../lib/img/cache.php
$path1 = &#39;/home/web/lib/img/cache.php&#39;;
$path2 = &#39;/xhome/web/show.php&#39;;
echo getRelativePath($path1, $path2).&#39;<br>&#39;; // ../../home/web/lib/img/cache.php
?>

本文讲解了通过php 计算两个文件之间的相对路径方法 ,更多相关内容请关注php中文网。

相关推荐:

讲解php获取指定日期的相关内容

详解PHP生成唯一RequestID类

如何通过MySQL查看数据库表容量大小

Atas ialah kandungan terperinci 通过php 计算两个文件之间的相对路径方法. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn