Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

removing dots and slashes regex - non relative

Tags:

regex

php

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/

like image 363
Mike Avatar asked Sep 07 '10 18:09

Mike


5 Answers

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

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

This outputs:

 /somefile/here/
like image 118
shamittomar Avatar answered Oct 02 '22 10:10

shamittomar


You could use the realpath() function PHP provides. This requires the file to exist, however.

like image 32
Jim Avatar answered Oct 02 '22 10:10

Jim


If I understood you correctly:

$path = "/".str_replace("../","","../../../somefile/here/");  
like image 38
fatnjazzy Avatar answered Oct 02 '22 08:10

fatnjazzy


This should work:

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

You can test it here.

like image 20
Vikash Avatar answered Oct 02 '22 10:10

Vikash


You could try :

<?php
$str = '../../../somefile/here/';
$str = preg_replace('~(?:\.\./)+~', '/', $str);
echo $str,"\n";
?>
like image 30
Toto Avatar answered Oct 02 '22 10:10

Toto