Santosh Patnaik's method worked in most cases, but when I gave it funky input with different directory separators it returned the wrong path. I liked julabz at laposte dot net the best, and modified it to use a similar signiture signature to Patnaik's function:
<?php
function unrealpath($start_dir, $final_dir, $dirsep = DIRECTORY_SEPARATOR){
$start_dir = str_replace('/',$dirsep,$start_dir);
$final_dir = str_replace('/',$dirsep,$final_dir);
$start_dir = str_replace('\\',$dirsep,$start_dir);
$final_dir = str_replace('\\',$dirsep,$final_dir);
$firstPathParts = explode($dirsep, $start_dir);
$secondPathParts = explode($dirsep, $final_dir);
$sameCounter = 0;
for($i = 0; $i < min( count($firstPathParts), count($secondPathParts) ); $i++) {
if( strtolower($firstPathParts[$i]) !== strtolower($secondPathParts[$i]) ) {
break;
}
$sameCounter++;
}
if( $sameCounter == 0 ) {
return $final_dir;
}
$newPath = '';
for($i = $sameCounter; $i < count($firstPathParts); $i++) {
if( $i > $sameCounter ) {
$newPath .= $dirsep;
}
$newPath .= "..";
}
if( strlen($newPath) == 0 ) {
$newPath = ".";
}
for($i = $sameCounter; $i < count($secondPathParts); $i++) {
$newPath .= $dirsep;
$newPath .= $secondPathParts[$i];
}
return $newPath;
}
?>
The only error I found in julabz's function was that count is always 1 for any string, but strlen does what he intended in this case.