Last active
November 2, 2015 10:57
-
-
Save charlestang/3f74c64c6a3fe59abfd3 to your computer and use it in GitHub Desktop.
计算 $b 相对于 $a 的路径的算法
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function rel($b, $a, $lvl = 1) { | |
$first_b = retrieve_first($b); | |
$first_a = retrieve_first($a); | |
if (!$first_a) { | |
return ltrim($b, '/'); | |
} | |
if (!$first_b) { | |
return '../' . rel($b, rm_first($a), $lvl); | |
} | |
if ($first_a == $first_b && $lvl) { | |
return rel(rm_first($b), rm_first($a), $lvl); | |
} else { | |
return '../' . rel($b, rm_first($a), 0); | |
} | |
} | |
function retrieve_first($str) { | |
$lpos = strpos($str, '/'); | |
$rpos = strrpos($str, '/'); | |
if ($lpos == $rpos) { | |
return ''; | |
} else { | |
return substr($str, 1, strpos($str, '/', 1) - 1); | |
} | |
} | |
function rm_first($str) { | |
return substr($str, strpos($str, '/', 1)); | |
} | |
$a = '/a/b/c/d/e.php'; | |
$b = '/a/b/12/34/c/f.php'; | |
$c = '/e.php'; | |
//echo retrieve_first($a), PHP_EOL; | |
//echo retrieve_first($b), PHP_EOL; | |
//echo retrieve_first($c), PHP_EOL; | |
//echo rm_first($a), PHP_EOL; | |
//echo rm_first($b), PHP_EOL; | |
//echo rm_first($c), PHP_EOL; | |
echo rel($a, $b), PHP_EOL; | |
//echo rel($b, $c), PHP_EOL; | |
//echo rel($c, $a), PHP_EOL; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment