/**
* @param $dirPath
* @return string
*/
function dirPathFormat($dirPath)
{
$dirPath = str_replace('\\', "/", $dirPath);
$parts = explode('/', $dirPath);
//首個路徑不用管,可能是'', '..', '.', '其他'
$first = array_shift($parts);
$path = [];
foreach ($parts as $part) {
if ($part === '.') {
//一個點代表當前路徑不用處理
continue;
} elseif ($part === '..' && end($path) !== false && end($path) !== '..') {
//這裏有可能前面有幾個雙點 比如 ../../../a/b/c
array_pop($path);
} else {
$path[] = $part;
}
}
array_unshift($path, $first);
return implode('/', $path);
}
var_dump(dirPathFormat('/a/d/.././f/1.jpg'));
var_dump(dirPathFormat('../../../c/d/../../../../f/1.jpg'));
運行結果
string(10) "/a/f/1.jpg"
string(22) "../../../../../f/1.jpg"