Last active
May 19, 2016 13:18
-
-
Save mogelbrod/a80eebbcaaba78f503a1c5a2ecf2729c to your computer and use it in GitHub Desktop.
Generate a relative URL from path A to B
This file contains hidden or 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 relativePath($from, $to) { | |
$fromAry = explode('/', $from); | |
$toAry = explode('/', $to); | |
while (count($fromAry) && count($toAry) && $fromAry[0] === $toAry[0]) { | |
array_shift($fromAry); | |
array_shift($toAry); | |
} | |
$up = count($fromAry); | |
if ($up > 0 && count($toAry)) $up--; | |
$relative = str_repeat('../', $up) . implode('/', $toAry); | |
if ($relative === '') $relative = basename($to); | |
return $relative; | |
} | |
$tests = [ | |
['a/b/c', 'a/b/c', 'c'], | |
['a/b/c', 'a/b/d', 'd'], | |
['a/b/c', 'a/b/d/g', 'd/g'], | |
['a/b/c', 'a/b', '../'], | |
['a/b/c', 'a', '../../'], | |
['a/b/c', 'e', '../../e'], | |
['a', 'a', 'a'], | |
['a', 'e', 'e'], | |
['a', 'e/f', 'e/f'], | |
]; | |
foreach ($tests as $test) { | |
list($from, $to, $expected) = $test; | |
$relative = relativePath($from, $to); | |
if ($relative !== $expected) { | |
echo "Fail: $from -> $to => $relative != $expected\n"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment