PHP Gets the relative path instance code

Source: Internet
Author: User
Keywords Web Programming PHP Tutorials
Tags array array_merge code function php php tutorial programming return

PHP Tutorial Get the relative Path instance code

function Getrelativepath ($a, $b) {
$returnPath = Array (dirname ($b));
$arrA = explode ('/', $a);
$arrB = explode ('/', $returnPath [0]);

    for ($n = 1, $len = count ($arrB), $n < $len; $n + +) {  
         if ($arrA [$n]!= $arrB [$n]) {  
             break;  
       }   
   }  
    if ($len-$n > 0) {  
         $returnPath = Array_merge ($returnPath, Array_fill (1, $len-$n, ' ... '));   
   }  
      
    $ Returnpath = Array_merge ($returnPath, Array_slice ($arrA, $n));  
    return implode ('/', $returnPath);  
}  
Var_dump (Getrelativepath ($a, $b);

Method Two
$a = "/a/b/c/d/index.php";
Echo basename ($a, '. php ');//Return the file name part of the path
echo dirname ($a);
$b = "/a/b/12/34/index2.php";

function Getrelativepath ($path 1, $path 2) {
$p 1 = dirname ($path 1);
$p 2 = dirname ($path 2);

$arr 1 = explode ('/', $p 1);
$arr 2 = explode ('/', $p 2);

    $diff _arr= Array_diff ($arr 2, $arr 1);   //calculation difference set notice who's here versus who's
     $inter _arr = Array_intersect ($arr 1, $arr 2);//Compute intersection
   
    $leng = count ($ Inter_arr);   //length is based on intersection. Section
    for ($i =1 $i < $leng $i + +) {
        $inter _arr[$i ] = '..';    
   }
   
    $merge _arr = Array_merge ($ Inter_arr, $diff _arr);
    $fina _arr = implode ('/', $merge _arr);
    return $fina _arr;
}
Var_dump (Getrelativepath ($a, $b));
//return string '/... /.. /12/34 ' (length=12)
//If changed to $diff_arr= Array_diff ($arr 1, $arr 2), return string '/... /.. /C/D (length=12)
 

Related Article

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.