Created
October 14, 2014 07:32
-
-
Save tesfabpel/63108b471e64f646a5e4 to your computer and use it in GitHub Desktop.
Returns a relative path base on two absolute paths (not including files)
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
function getRelativePath($base = '/', $target = '/') | |
{ | |
$out = array(); | |
$base_ex = explode('/', $base); | |
$target_ex = explode('/', $target); | |
//Find common ancestor | |
$max = min(count($base_ex), count($target_ex)); | |
for($i = 0; $i < $max; $i++) | |
{ | |
$b = $base_ex[$i]; | |
$t = $target_ex[$i]; | |
if($b != $t) break; | |
} | |
$common = $i; | |
$diff = (count($base_ex) - 1) - $common; | |
/* | |
$diff = 0: | |
Target: /httpdocs/admin/ | |
Base: /httpdocs/admin/ | |
$diff > 0: | |
Target: /httpdocs/ | |
Base: /httpdocs/admin/ | |
*/ | |
for($i = 0; $i < $diff; $i++) | |
{ | |
$out[] = '..'; | |
} | |
$rest = array_slice($target_ex, $common); | |
$out = array_merge($out, $rest); | |
if(count($out) == 0) $out[] = '.'; | |
return join('/', $out); | |
} | |
echo getRelativePath('/httpdocs/admin/', '/httpdocs/admin/img/icons/'); | |
echo "\n"; | |
echo getRelativePath('/httpdocs/admin/', '/httpdocs/admin/'); | |
echo "\n"; | |
echo getRelativePath('/httpdocs/admin/', '/httpdocs/img/'); | |
echo "\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment