Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 633
Hasen Avatar asked Aug 28 '17 06:08

Hasen


1 Answers

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.
like image 58
Wiktor Stribiżew Avatar answered Nov 18 '22 10:11

Wiktor Stribiżew