Skip to content

Instantly share code, notes, and snippets.

@t-cyrill
Created July 4, 2013 08:43
Show Gist options
  • Save t-cyrill/5926021 to your computer and use it in GitHub Desktop.
Save t-cyrill/5926021 to your computer and use it in GitHub Desktop.
<?php
$path_samples = array(
'/temp/hoge/foo',
'/temp/./hoge/foo',
'/temp//hoge/foo',
'/temp///hoge/foo',
'/temp//bar/../hoge/foo',
'/temp/bar/../../../..//temp//bar/../hoge/foo',
'/temp/bar/../../../..//temp//bar/../hoge/foo////',
);
foreach ($path_samples as $path) {
echo normalize_path($path);echo "\n";
}
function normalize_path($path) {
$delimiter = DIRECTORY_SEPARATOR;
$splited = explode($delimiter, $path);
$realpath_stack = array();
foreach ($splited as $name) {
switch ($name) {
case '..':
array_pop($realpath_stack);
continue;
case '.':
case '':
continue;
default:
$realpath_stack[] = $name;
}
}
return $delimiter.implode($delimiter, $realpath_stack);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment