views:

280

answers:

4

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
+3  A: 

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 any no more than two consecutive slashes):

$str = str_replace('//', '/', $str);
Alix Axel
Much shorter than expected. I could not make it fail. Thanks!
Jens Törnell
str_replace won't do like this. you need a recursive function I believe. (take a look below)
sombe
As Gal says, the str_replace won't work if there are more than two slashes. The preg_replace will work but Bart K's version is better because it doesn't match single slashes, just two or more
meouw
@Gal: Fixed. =)
Alix Axel
@meouw: Thanks, I was in doubt with that one - fixed now.
Alix Axel
+2  A: 

Try:

echo preg_replace('#/{2,}#', '/', '////%postname%//mytest/test///testing');
Bart Kiers
A: 
echo str_replace('//', '/', $str);
powtac
No, that will replace `'////'` with `'//'` while a single slash is needed here.
Bart Kiers
A: 
function drop_multiple_slashes($str)
{
  if(strpos($str,'//')!==false)
  {
     return drop_multiple_slashes(str_replace('//','/',$str));
  }
  return $str;
}

that's using str_replace

sombe
That won't work unless you change _!== 0_ to _!== false_. Plus, there's no need for recursion: _while (strpos($str, '//') !== false) { $str = str_replace('//', '/', $str); } return $str;_
GZipp
@GZipp, you're right, I edited it. As far as I know, there is no difference in performance between recursive function and while loop (but I could gladly be proven otherwise).
sombe