Skip to content

Instantly share code, notes, and snippets.

@tesfabpel
Created October 14, 2014 07:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tesfabpel/63108b471e64f646a5e4 to your computer and use it in GitHub Desktop.
Save tesfabpel/63108b471e64f646a5e4 to your computer and use it in GitHub Desktop.
Returns a relative path base on two absolute paths (not including files)
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