regex, :
function simplify_path($path, $directory_separator = "/", $equivalent = true){
$path = trim($path);
$prepend = (substr($path,0,1) == $directory_separator)?$directory_separator:"";
$path_array = explode($directory_separator, $path);
if($prepend) array_shift($path_array);
$output = array();
foreach($path_array as $val){
if($val != '..' || ((empty($output) || $last == '..') && $equivalent)) {
if($val != '' && $val != '.'){
array_push($output, $val);
$last = $val;
}
} elseif(!empty($output)) {
array_pop($output);
}
}
return $prepend.implode($directory_separator,$output);
}
:
echo(simplify_path("../../../one/no/no/../../two/no/../three"));
echo(simplify_path("/../../one/no/no/../../two/no/../three"));
echo(simplify_path("/one/no/no/../../two/no/../three"));
echo(simplify_path(".././../../one/././no/./no/../../two/no/../three"));
echo(simplify_path(".././..///../one/.///./no/./no/../../two/no/../three/"));
I thought it would be better to return an equivalent string, so I respected the appearance ..at the beginning of the string.
If you do not want them, you can call it using the third parameter $ equivalent = false:
echo(simplify_path("../../../one/no/no/../../two/no/../three", "/", false));
echo(simplify_path("/../../one/no/no/../../two/no/../three", "/", false));
echo(simplify_path("/one/no/no/../../two/no/../three", "/", false));
echo(simplify_path(".././../../one/././no/./no/../../two/no/../three", "/", false));
echo(simplify_path(".././..///../one/.///./no/./no/../../two/no/../three/", "/", false));
source
share