Skip to content

Instantly share code, notes, and snippets.

@mageekguy
Created February 14, 2013 10:39
Show Gist options
  • Save mageekguy/4951920 to your computer and use it in GitHub Desktop.
Save mageekguy/4951920 to your computer and use it in GitHub Desktop.
static public function relativise($path, $workingpath = null) {
if(is_null($workingpath)) $workingpath = self::CorrectPathSlashes(getcwd());
$path = preg_replace('#([^/]+/\.\.)#', '', $path);
$path = preg_replace('#(\./|/\.$)#', '', $path);
$path = preg_replace('#/{2,}#', '/', $path);
$path = preg_replace('#/$#', '', $path);
$workingpath = preg_replace('#([^/]+/\.\.)#', '', $workingpath);
$workingpath = preg_replace('#(\./|/\.$)#', '', $workingpath);
$workingpath = preg_replace('#/{2,}#', '/', $workingpath);
$workingpath = preg_replace('#/$#', '', $workingpath);
$path = explode('/', $path);
if($path[0] !== '') {
return implode('/', $path);
} else {
$workingpath = explode('/', $workingpath);
$i=count($workingpath);
$relativepath = array();
$wp = array_combine(array_reverse(array_keys($workingpath)), array_reverse($workingpath));
foreach($wp as $n=>$part){
if(!isset($path[$n]) || $path[$n]!=$part) {$relativepath[] = '..'; $i = $n;}
}
$relativepath = array_reverse($relativepath);
for($c=count($path), $end=false; $i < $c && !$end; $i++) {
$relativepath[] = $path[$i];
}
$relativepath = implode('/', $relativepath);
}
return $relativepath;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment