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));
?>