I already read about realpath(), but is there a function that I can pass a base directory and a filename that would give me the following result without resolvi
function normalize_path($path, $pwd = '/') {
if (!isset($path[0]) || $path[0] !== '/') {
$result = explode('/', getcwd());
} else {
$result = array('');
}
$parts = explode('/', $path);
foreach($parts as $part) {
if ($part === '' || $part == '.') {
continue;
} if ($part == '..') {
array_pop($result);
} else {
$result[] = $part;
}
}
return implode('/', $result);
}
(The question was tagged PHP at the time I wrote this.)
Anyway, here is a regex version:
function normalize_path($path, $pwd = '/') {
if (!isset($path[0]) || $path[0] !== '/') {
$path = "$pwd/$path";
}
return preg_replace('~
^(?P>sdotdot)?(?:(?P>sdot)*/\.\.)*
|(?(?:(?P>sdot)*/(?!\.\.)(?:[^/]+)(?P>sdotdot)?(?P>sdot)*/\.\.)+)
|(?/\.?(?=/|$))+
~sx', '', $path);
}