Matching multiple occurrence of the same character with preg_match

♀尐吖头ヾ 提交于 2019-12-07 21:30:50

问题


how can i find multiple occurrence of the same character? something like:

$maxRepeat = 3;

"pool" passes

"poool" don't

i need this to work for any character, so i guess I'll have to escape special characters like . and \

which characters i have to escape?

do you know any good reference to preg_match regexp apart from the one on php.net?


回答1:


You use quantifiers for this

preg_match("/p(o){1,3}ls/",$string);

Excerpt:

The following standard quantifiers are recognized:

1. * Match 0 or more times
2. + Match 1 or more times
3. ? Match 1 or 0 times
4. {n} Match exactly n times
5. {n,} Match at least n times
6. {n,m} Match at least n but not more than m times

My favorite resource for learning Perl Regular Expressions is the time honored camel book. But if you don't have one handy, this site is pretty good.




回答2:


found, what i need is

if(preg_match('/(.)\1/', $t)) return true;

this returns true for $t = 'aa'; // any char

if(preg_match('/(.)\1\1/', $t)) return true;

this returns true for $t = 'aaa'; // any char

and so on




回答3:


/.{1,2}/         # 2 is limit, 1 to have at least one character

any character repeated up to so many times, you'll have to format your regex if your $amxRepeate is an int.



来源:https://stackoverflow.com/questions/1637941/matching-multiple-occurrence-of-the-same-character-with-preg-match

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