我想检查字符串是否包含大于或等于字母/数字的3倍,并将其替换为只有一个字母/数字。例如:
IIIII havvvvve a bigggg tesssssttttt tomorrow soooo iiii 2222551111 haveeee to do this rightttttt
变得像这样
I have a big test tomorrow so i 2551 have to do this right.
如何使用preg_replace
完成此操作?
答案 0 :(得分:3)
<强>正则表达式:强>
([A-Za-z0-9])\1\1+
这将匹配超过或等于字母/数字的3倍并捕获第一个字母或数字。最后,整个字符串被组索引1中的字符替换。
替换字符串:
\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);
?>
<强>输出:强>
I have a big test tomorrow so i 2551 have to do this right
答案 1 :(得分:2)