Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression, replace multiple slashes with only one

It seems like an easy problem to solve, but It's not as easy as it seems. I have this string in PHP:

////%postname%/

This is a URL and I never want more than one slash in a row. I never want to remove the slashes completely.

This is how it should look like:

/%postname%/

Because the structure could look different I need a clever preg replace regexp, I think. It need to work with URLS like this:

////%postname%//mytest/test///testing

which should be converted to this:

/%postname%/mytest/test/testing
like image 938
Jens Törnell Avatar asked Feb 07 '10 18:02

Jens Törnell


1 Answers

Here you go:

$str = preg_replace('~/+~', '/', $str);

Or:

$str = preg_replace('~//+~', '/', $str);

Or even:

$str = preg_replace('~/{2,}~', '/', $str);

A simple str_replace() will also do the trick (if there are no more than two consecutive slashes):

$str = str_replace('//', '/', $str);
like image 185
Alix Axel Avatar answered Sep 28 '22 07:09

Alix Axel