Jens Törnell
Jens Törnell

Reputation: 24748

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

Upvotes: 6

Views: 10953

Answers (7)

Nolwennig
Nolwennig

Reputation: 1684

do $str = str_replace('//', '/', $str, $count); while($count);

Upvotes: 0

Thomas Decaux
Thomas Decaux

Reputation: 22661

My solution:

while (strlen($uri) > 1 && $uri[0] === '/' && $uri[1] === '/') {
    $uri = substr($uri, 1);
}

Upvotes: 0

Kerem
Kerem

Reputation: 11566

Late but all these methods will remove http:// slashes too, but this.

function to_single_slashes($input) {
    return preg_replace('~(^|[^:])//+~', '\\1/', $input);
}

# out: http://localhost/lorem-ipsum/123/456/
print to_single_slashes('http:///////localhost////lorem-ipsum/123/////456/');

Upvotes: 5

Alix Axel
Alix Axel

Reputation: 154513

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);

Upvotes: 21

Gal
Gal

Reputation: 23662

function drop_multiple_slashes($str)
{
  if(strpos($str,'//')!==false)
  {
     return drop_multiple_slashes(str_replace('//','/',$str));
  }
  return $str;
}

that's using str_replace

Upvotes: 4

powtac
powtac

Reputation: 41040

echo str_replace('//', '/', $str);

Upvotes: -1

Bart Kiers
Bart Kiers

Reputation: 170138

Try:

echo preg_replace('#/{2,}#', '/', '////%postname%//mytest/test///testing');

Upvotes: 4

Related Questions