Removing dots and oblique regular expressions are not relative

how can I remove trailing slashes and dots from a path unrelated to the root.

For example ../../../somefile/here/ (regardless of depth), so I just get /somefile/here/

+4
source share
6 answers

No regex needed, use ltrim() with /. . Like this:

  echo "/".ltrim("../../../somefile/here/", "/."); 

It is output:

  /somefile/here/ 
+7
source

You can use the realpath () function provided by PHP. However, this requires the file to exist.

+2
source

If you understand correctly:

 $path = "/".str_replace("../","","../../../somefile/here/"); 
+2
source

This should work:

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

You can test it here .

+1
source

You can try:

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

(\.*/)*(?<capturegroup>.*)

The first group matches a number of points, followed by a slash, an unlimited number of times; the second group is what interests you. This will separate your slash, so add a slash.

Remember that this absolutely does not confirm that your leading line of slashes and periods is not something plainly stupid. However, it will not remove leading points from your path, as an obvious pattern ([./])* for the first group; it finds the longest chain of dots and slashes that ends with a slash, so it wonโ€™t hurt your real path if it starts with a dot.

Keep in mind that the obvious "/". The ltrim () strategy will strip leading points from directory names, which is bad if your first directory is completely plausible, because leading points are used for hidden directories.

0
source

All Articles