I want to check if a string contains more than or equals 3 times a letter/number and replace it with only one letter/number. For example:
IIIII havvvvve a bigggg tesssssttttt tomorrow soooo iiii 2222551111 haveeee to do this rightttttt
To became like this
I have a big test tomorrow so i 2551 have to do this right.
How can this be done with preg_replace
?
Regex:
([A-Za-z0-9])\1\1+
This would match more than or equals 3 times a letter/number and captures the first letter or Number. Finally the whole string was replaced with the character in the group index 1.
Replacement string:
\1
<?php
$text = 'IIIII havvvvve a bigggg tesssssttttt tomorrow soooo iiii 2222551111 haveeee to do this rightttttt';
$pattern = '~([A-Za-z0-9])\1\1+~';
echo preg_replace($pattern,'\1',$text);
?>
Output:
I have a big test tomorrow so i 2551 have to do this right
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.