Skip to content

Instantly share code, notes, and snippets.

@ohaal
Created June 15, 2012 11:47
Show Gist options
  • Save ohaal/2936041 to your computer and use it in GitHub Desktop.
Save ohaal/2936041 to your computer and use it in GitHub Desktop.
Find the relative path between two paths
/**
*
* Find the relative file system path between two file system paths
*
* @param string $frompath Path to start from
* @param string $topath Path we want to end up in
*
* @return string Path leading from $frompath to $topath
*/
function find_relative_path ( $frompath, $topath ) {
$from = explode( DIRECTORY_SEPARATOR, $frompath ); // Folders/File
$to = explode( DIRECTORY_SEPARATOR, $topath ); // Folders/File
$relpath = '';
$i = 0;
// Find how far the path is the same
while ( isset($from[$i]) && isset($to[$i]) ) {
if ( $from[$i] != $to[$i] ) break;
$i++;
}
$j = count( $from ) - 1;
// Add '..' until the path is the same
while ( $i <= $j ) {
if ( !empty($from[$j]) ) $relpath .= '..'.DIRECTORY_SEPARATOR;
$j--;
}
// Go to folder from where it starts differing
while ( isset($to[$i]) ) {
if ( !empty($to[$i]) ) $relpath .= $to[$i].DIRECTORY_SEPARATOR;
$i++;
}
// Strip last separator
return substr($relpath, 0, -1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment