开发者

removing dots and slashes regex - non relative

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/开发者_StackOverflow社区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/");  


This should work:

<?php
echo "/".preg_replace('/\.\.\/+/',"","../../../somefile/here/")
?>

You can test it here.


You could try :

<?php
$str = '../../../somefile/here/';
$str = preg_replace('~(?:\.\./)+~', '/', $str);
echo $str,"\n";
?>


(\.*/)*(?<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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜