PHP function calculates the relative path of two files

Source: Internet
Author: User
Tags count explode relative return

Sina has an interview topic: Write a PHP function to calculate the relative path of two files? PHP//Calculate the relative path of c.php relative to e.php should be ... /.. /12/34 $a =/a/b/c/d/e.php; $b =/a/b/12/34/c.php; GetPathInfo ($a, $b); function GetPathInfo ($a, $b) {$a

Sina has an interview topic: Write a PHP function to calculate the relative path of two files

  

Calculating the relative path of c.php relative to e.php should be ... /.. /12/34

$a = '/a/b/c/d/e.php ';

$b = '/a/b/12/34/c.php ';

GetPathInfo ($a, $b);

function GetPathInfo ($a, $b) {

$a 2array = explode ('/', $a);

$b 2array = explode ('/', $b);

$pathinfo = ';

for ($i = 1; $i <= count ($b 2array)-2; $i + +) {

$pathinfo. = $a 2array[$i] = = $b 2array[$i]? '.. /': $b 2array[$i]. ' /';

}

Print_r ($pathinfo);

}

?>

There's a more complicated approach. It's not perfect. Thinking is right can be studied

  

$a = ' aa/bb/cc/dd/a.php ';

$b = ' aa/bb/11/22/33/b.php ';

Write a function that counts the relative paths of two files.

function Getnum ($variant, $variant 2) {

$pth 1 = null;

$pth 2 = null;

$tmp = Array ();

Separately determine if the path below the file is not present.

if (Is_file ($variant) && is_file ($variant 2)) {

$len 1 = count ($pth 1 = explode ('/', dirname ($variant)));

$len 2 = count ($pth 2 = explode ('/', DirName ($variant 2)));

$maxlen = max ($len 1, $len 2);

for ($i =1; $i < $maxlen; $i + +) {

if ($pth 1[$i]!= $pth 2[$i] && isset ($pth 1[$i])) {

if (Isset ($pth 2[$i])) $tmp [] = $pth 2[$i];

}else{

$tmp [] = $pth 2[$i];

$pathe. = '.. /';

}

}

Return $pathe. Implode ('/', $tmp). ' /'. BaseName ($variant 2);

}else{

Return ' path illegal! '

}

}

Print_r (Getnum ($a, $b));

?>



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.