PHP Preg-Replace more than one underscore

How do I, using preg_replace, replace more than one underscore with just one underscore?


Solution 1:

The + operator (quantifier) matches multiple instances of the last character (, character class or capture group or back-reference).

$string = preg_replace('/_+/', '_', $string);

This would replace one or more underscores with a single underscore.


Technically more correct to the title of the question then is to only replace two or more:

$string = preg_replace('/__+/', '_', $string);

Or writing the quantifier with braces:

$string = preg_replace('/_{2,}/', '_', $string);

And perhaps then to capture and (back-) reference:

$string = preg_replace('/(_)\1+/', '\1', $string);

Solution 2:

preg_replace('/[_]+/', '_', $your_string);

Solution 3:

Actually using /__+/ or /_{2,}/ would be better than /_+/ since a single underscore does not need to be replaced. This will improve the speed of the preg variant.