Skip to content

Instantly share code, notes, and snippets.

@charlestang
Last active November 2, 2015 10:57
Show Gist options
  • Save charlestang/3f74c64c6a3fe59abfd3 to your computer and use it in GitHub Desktop.
Save charlestang/3f74c64c6a3fe59abfd3 to your computer and use it in GitHub Desktop.
计算 $b 相对于 $a 的路径的算法
<?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