3v4l.org

run code in 300+ PHP versions simultaneously
<?php /** * * 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); } var_dump(find_relative_path('D:/test/pokus/', 'D:/test/some/file'));
Output for 4.3.0 - 4.3.11, 4.4.0 - 4.4.9, 5.0.0 - 5.0.5, 5.1.0 - 5.1.6, 5.2.0 - 5.2.17, 5.3.0 - 5.3.29, 5.4.0 - 5.4.45, 5.5.0 - 5.5.38, 5.6.0 - 5.6.38, 7.0.0 - 7.0.31, 7.1.0 - 7.1.33, 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.28, 8.2.0 - 8.2.18, 8.3.0 - 8.3.6
string(12) "../some/file"

preferences:
270.73 ms | 406 KiB | 448 Q