我一直在网上搜索一个解决方案,但找不到。
我需要删除字符串中的重复字符,但也希望包含一个异常,以允许字符串中重复/保留整数字符数量。
例如,,我尝试了以下方法:
$str = 'This ----------is******** a bbbb 999-999-9999 ******** 8888888888 test 4444444444 ********##########Sammy!!!!!! ###### hello !!!!!!';
$t1 = preg_replace('/(.)\1{3,}/','',$str);
$t2 = preg_replace('/(\S)\1{3,}/','',$str);
$t3 = preg_replace('{(.)\1+}','$1',$str);
$t4 = preg_replace("/[;,:\s]+/",',',$str);
$t5 = preg_replace('/\W/', '', $str);
$t6 = preg_replace( "/[^a-z]/i", "", $str);
echo '$t1 = '.$t1.'<br>';
echo '$t2 = '.$t2.'<br>';
echo '$t3 = '.$t3.'<br>';
echo '$t4 = '.$t4.'<br>';
echo '$t5 = '.$t5.'<br>';
echo '$t6 = '.$t6.'<br>';结果:
$t1 = This is a 999-999- test Sammy hello
$t2 = This is a 999-999- test Sammy hello
$t3 = This -is* a b 9-9-9 * 8 test 4 *#Samy! # helo !
$t4 = This,----------is********,a,bbbb,999-999-9999,********,8888888888,test,4444444444,********##########Sammy!!!!!!,######,hello,!!!!!!
$t5 = Thisisabbbb99999999998888888888test4444444444Sammyhello
$t6 = ThisisabbbbtestSammyhello所需的输出将是:
This ---is*** a bbbb 999-999-9999 *** 8888888888 test 4444444444 ***###Sammy!!! ### hello !!!如您所见,所需的输出只留下数字,只留下3个重复字符,即- ### *!
如果可能的话,我希望能够将异常从3更改为任何其他整数。
提前谢谢。
发布于 2012-05-25 21:48:52
这样可以做到:
preg_replace('/(([^\d])\2\2)\2+/', '$1', $str);[^\d]匹配一个不是数字的字符。
\2指的是捕获的数字
$1指的是第一个捕获的组,它将是前三个重复字符,因此多余的\2+被去掉。
发布于 2012-05-25 21:56:52
正在寻找的正则表达式:/((.)\2{2})\2*/ (如果需要异常n ),将n-1放在大括号{n-1}:/((.)\2{n-1})\2*/中
编辑:对于非数字或任何事情,请用其他东西替换.,例如[^\d]等. /(([^\d])\2{2})\2*/。
https://stackoverflow.com/questions/10761403
复制相似问题