それを行う既存のPHP関数、またはxdazzの答えに沿った単純なものを見つけたいと思っていました(しかし、それは実際には私が望むように機能します)。そのような答えを見つけることができなかったので、私は自分の汚い関数を書きました。改善のためのコメントや提案をいただければ幸いです。
// return the contracted path (e.g. '/dir1/dir2/../dir3/filename' => '/dir1/dir3/filename')
// $path: an absolute or relative path
// $rel: the base $path is given relatively to - if $path is a relative path; NULL would take the current working directory as base
// return: the contracted path, or FALSE if $path is invalid
function contract_path($path, $rel = NULL) {
if($path == '') return FALSE;
if($path == '/') return '/';
if($path[strlen($path) - 1] == '/') $path = substr($path, 0, strlen($path) - 1); // strip trailing slash
if($path[0] != '/') { // if $path is a relative path
if(is_null($rel)) $rel = getcwd();
if($rel[strlen($rel) - 1] != '/') $rel .= '/';
$path = $rel . $path;
}
$comps = explode('/', substr($path, 1)); // strip initial slash and extract path components
$res = Array();
foreach($comps as $comp) {
if($comp == '') return FALSE; // double slash - invalid path
if($comp == '..') {
if(count($res) == 0) return FALSE; // parent directory of root - invalid path
array_pop($res);
}
elseif($comp != '.') $res[] = $comp;
}
return '/' . implode('/', $res);
}