Mike
Mike

Reputation: 59

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/here/

Upvotes: 5

Views: 4913

Answers (6)

Toto
Toto

Reputation: 91488

You could try :

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

Upvotes: 1

Vikash
Vikash

Reputation: 989

This should work:

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

You can test it here.

Upvotes: 1

Adam Norberg
Adam Norberg

Reputation: 3076

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

Upvotes: 0

fatnjazzy
fatnjazzy

Reputation: 6152

If I understood you correctly:

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

Upvotes: 2

Jim
Jim

Reputation: 18863

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

Upvotes: 4

shamittomar
shamittomar

Reputation: 46692

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

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

This outputs:

 /somefile/here/

Upvotes: 8

Related Questions