PHP - Need to remove duplicate characters within a String but would like to include exceptions

a 夏天 提交于 2019-12-01 11:15:25

This will do it:

preg_replace('/(([^\d])\2\2)\2+/', '$1', $str);

[^\d] matches a single character which isn't a digit.
\2 refers to the captured digit
$1 refers to the first captured group which will be the first three repeated characters, so the extra \2+ gets stripped off.

Codepad

The regex you are looking for: /((.)\2{2})\2*/ If you need exception n, put n-1 in the curly brace {n-1}: /((.)\2{n-1})\2*/

EDIT: for non-number or what ever you what, replace . with other things, for example [^\d] etc. /(([^\d])\2{2})\2*/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!