【问题标题】:Matching multiple occurrence of the same character with preg_match使用 preg_match 匹配多次出现的相同字符
【发布时间】:2010-12-10 21:51:47
【问题描述】:

我怎样才能找到同一个字符的多次出现? 类似:

$maxRepeat = 3;

"pool" passes

"poool" don't

我需要它适用于任何字符,所以我想我必须转义特殊字符,例如 .和 \

我必须转义哪些字符?

除了 php.net 上的那个之外,你知道对 preg_match regexp 的任何好的参考吗?

【问题讨论】:

    标签: php regex preg-match


    【解决方案1】:

    找到了,我需要的是

    if(preg_match('/(.)\1/', $t)) 返回真;

    $t = 'aa' 时返回 true; // 任何字符

    if(preg_match('/(.)\1\1/', $t)) 返回真;

    $t = 'aaa' 时返回 true; // 任何字符

    等等

    【讨论】:

      【解决方案2】:

      您为此使用quantifiers

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

      摘录:

      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
      

      我最喜欢的学习Perl Reg正则表达式的资源是久负盛名的camel book。但如果你手边没有一台,this site 还是不错的。

      【讨论】:

      • 我认为他希望正则表达式适用于任何字符串,而不仅仅是池,而不仅仅是重复的字母 o - 比如$string = 'aaaaany word';
      【解决方案3】:
      /.{1,2}/         # 2 is limit, 1 to have at least one character
      

      任何重复多次的字符,如果您的 $amxRepeate 是 int,则必须格式化您的正则表达式。

      【讨论】:

      • dot 将匹配任何字符,而不是相同的字符重复。所以“oo”会匹配,但“ao”也会匹配
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多