How to calculate the relative path between two files in PHP

Source: Internet
Author: User
Tags explode relative

For example:

The path to file A is/home/web/lib/img/cache.php

The path to file B is/home/web/api/img/show.php

So, the path to file a relative to File B is ... /.. /lib/img/cache.php, that is, file B accesses the relative path of file a.

function Getrelativepath

<?php  
/** calculates the path1 relative to path2 path, that is, the relative path of path2 reference paht1 
* @param  string $path 1 
* @param  string $ path2 
* @return String
/function Getrelativepath ($path 1, $path 2) {  
    $arr 1 = explode ('/', $path 1);  
    $arr 2 = explode ('/', $path 2);  
      
    Gets part of the same path  
    $intersection = Array_intersect_assoc ($arr 1, $arr 2);  
      
    $depth = 0;  
      
    For ($i =0, $len =count ($intersection); $i < $len; $i + +) {  
        if (!isset ($intersection [$i])) {  
            $depth = $i;  
            break;  
        }  
    }  
      
    To path2 the/into. /,path1 gets the back part and then  
    $tmp = Array_merge (Array_fill (0, Count ($arr 2)-$depth-1, ' ... '), Array_slice ($arr 1, $depth));  
      
    $relativePath = implode ('/', $tmp);  
      
    return $relativePath;  
>

Demo

<?php  
$path 1 = '/home/web/lib/img/cache.php ';  
$path 2 = '/home/web/api/img/show.php ';  
      
Echo Getrelativepath ($path 1, $path 2); // .. /.. /lib/img/cache.php  
?>

See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/webkf/PHP/

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.