Created
July 25, 2014 08:57
-
-
Save nyamsprod/554d9cbba9b2ada95b52 to your computer and use it in GitHub Desktop.
get a relative path from another path
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| header('Content-Type: text/html; charset=utf-8'); | |
| function getRelativePath($path, $reference) | |
| { | |
| //normalisation des parametres | |
| $path = (string) $path; | |
| if ('/' == $path[0]) { | |
| $path = substr($path, 1); | |
| } | |
| $reference = (string) $reference; | |
| if ('/' == $reference[0]) { | |
| $reference = substr($reference, 1); | |
| } | |
| $reference = explode('/', $reference); | |
| $path = explode('/', $path); | |
| array_map('urldecode', $reference); | |
| array_map('urldecode', $path); | |
| //si les 2 path sont identiques on retourne une string vide | |
| if ($path == $reference) { | |
| return ''; | |
| } | |
| $filename = array_pop($path); //on ne touche pas au filename (ie le dernier segment du path) | |
| // on determine l'index du dernier segment consecutif en fonction du path de reference | |
| $index = 0; | |
| foreach ($reference as $offset => $value) { | |
| if (! isset($path[$offset]) || $value != $path[$offset]) { | |
| break; | |
| } | |
| $index++; | |
| } | |
| //on deduit le nombre de segment identique en fonction du path de reference | |
| $start_index = count($reference) - $index; | |
| $res = array_merge( | |
| array_fill(0, $start_index, '..'), | |
| array_slice($path, $index), | |
| array($filename) | |
| ); | |
| array_map('rawurlencode', $res); | |
| return implode('/', $res); | |
| } | |
| /** | |
| * Example Code Usage | |
| */ | |
| $tests = array( | |
| array( | |
| 'path' => '/path/to/my/file.php', | |
| 'ref' => '/path/to/parent.php', | |
| 'test' => 'Reference path is a parent directory', | |
| ), | |
| array( | |
| 'path' => '/path/to/my/file.php', | |
| 'ref' => '/path/to/my/other_file.php', | |
| 'test' => 'reference path in the same directory' | |
| ), | |
| array( | |
| 'path' => '/path/to/my/file.php', | |
| 'ref' => '/path/to/my/other/file.php', | |
| 'test' => 'reference path in a child directory' | |
| ), | |
| array( | |
| 'path' => '/path/to/my/file.php', | |
| 'ref' => '/path/to/my/file.php', | |
| 'test' => 'reference path is the same' | |
| ), | |
| ); | |
| echo '<pre>', PHP_EOL; | |
| foreach ($tests as $args) { | |
| $res = getRelativePath($args['path'], $args['ref']); | |
| echo $args['test'], PHP_EOL, | |
| "PATH: ", $args['path'], PHP_EOL, | |
| "REFERENCE: ", $args['ref'], PHP_EOL, | |
| "RELATIVE PATH: ", var_export($res, true), PHP_EOL, | |
| "---", PHP_EOL, PHP_EOL; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment