Hasen Hasen - 2 months ago 20
PHP Question

PHP Regex reduce a repeated character to a single instance

I want to rid a text for repeated exclamation marks (!!!), question marks (??) or full stops (....) and replace them with a single instance of themselves. So I need "one preg_replace to rule them all" basically.

I currently have three separate patterns being executed:

preg_replace("/[!]{2,}/","!", $str);
preg_replace("/[?]{2,}/","?", $str);
preg_replace("/[.]{2,}/",".", $str);


Is there a way to replace the found character with a single instance of itself using just one regex pattern?

I need to turn:

Ok!!!
Really????
I guess.....


into:

Ok!
Really?
I guess.


With one regex pattern.

Answer Source

Use a capturing group with a backreference:

([?!.])\1+

Replace with $1.

See the regex demo.

Details

  • ([?!.]) - matches and captures into Group 1 a single char: ?, ! or .
  • \1+ - matches one or more instances of the content captured into Group 1.

PHP demo:

$str = "Ok!!!\nReally????\nI guess.....";
$res = preg_replace('/([?!.])\1+/', '$1', $str);
echo $res;

Results:

Ok!
Really?
I guess.