5

I replace all spaces with hyphens in my script like this:

$final = str_replace(' ','-',$final); The - is the only thing I replace.

What I'm replacing are Band Name - Song Name So in this case, if I had something like:

Metallica - Hero of the Day

I end up with:

 Metallica---Hero-of-the-Day

Notice the 3 --- there?

Can you suggest an elegant way of ending up with just one - instead of 3.

I can keep doing str_replace until it's done, but that doesn't see right.

jmenezes
  • 1,888
  • 6
  • 28
  • 44

1 Answers1

14

Use a regular expression changing multiple spaces or hyphens with one hyphen:

$final = preg_replace('#[ -]+#', '-', $text);
Peter van der Wal
  • 11,141
  • 2
  • 21
  • 29