how could I remove the trailing slashes and dots from a non root-relative path.
For instance, ../../../somefile/here/
(independently on how deep it is) so I just get /somefile/here/
how could I remove the trailing slashes and dots from a non root-relative path.
For instance, ../../../somefile/here/
(independently on how deep it is) so I just get /somefile/here/
No regex needed, rather use ltrim()
with /.
. Like this:
echo "/".ltrim("../../../somefile/here/", "/.");
This outputs:
/somefile/here/
You could use the realpath() function PHP provides. This requires the file to exist, however.
If I understood you correctly:
$path = "/".str_replace("../","","../../../somefile/here/");
(\.*/)*(?<capturegroup>.*)
The first group matches some number of dots followed by a slash, an unlimited number of times; the second group is the one you're interested in. This will strip your leading slash, so prepend a slash.
Beware that this is doing absolutely no verification that your leading string of slashes and periods isn't something patently stupid. However, it won't strip leading dots off your path, like the obvious ([./])*
pattern for the first group would; it finds the longest string of dots and slashes that ends with a slash, so it won't hurt your real path if it begins with a dot.
Be aware that the obvious "/." ltrim() strategy will strip leading dots from directory names, which is Bad if your first directory has one- entirely plausible, since leading dots are used for hidden directories.
You could try :
<?php
$str = '../../../somefile/here/';
$str = preg_replace('~(?:\.\./)+~', '/', $str);
echo $str,"\n";
?>