Replace multiple occurrences of same symbol using preg_replace?

kasperwf picture kasperwf · Jul 22, 2010 · Viewed 9.4k times · Source

Let's say I have a string like this:

$string = "hello---world";

How would I go about replacing the --- with a single hyphen? The string could easily look like this instead:

$string = "hello--world----what-up";

The desired result should be:

$string = "hello-world-what-up";

Answer

Mark Baker picture Mark Baker · Jul 22, 2010
$string = preg_replace('/-{2,}/','-',$string);