preg表达式匹配除“chr”组之外的四个连续辅音

时间:2013-12-12 20:49:22

标签: php regex

$string = "sqrtpdrt"; // matched
$string = "qwntfschrprtkjs"; // not matched (contains chr group) 

我用

preg_match('/[bcdfghjklmnpqrstvwxz]{4}/i', $string )

匹配4个连续辅音,但现在我要排除包含" chr"基。

1 个答案:

答案 0 :(得分:3)

这不是世界上最好的模式,但必须做到这一点:

preg_match('~(?!.*chr)^.*[bcdfghj-np-tvwxz]{4}~si', $string);

模式细节:

~                     # pattern delimiter
(?!.*chr)             # negative lookahead: not followed by something and "chr"
^                     # start of the string anchor
.*                    # anything zero or more times
[bcdfghj-np-tvwxz]{4} # (it's shorter with ranges!)
~si                   # the s modifier allows the dot to match newlines

你也可以这样做:

preg_match('~(?=.*[bcdfghj-np-tvwxz]{4})^(?>[^c]++|c(?!hr))+$~is', $string);

模式细节:

~
(?=.*[bcdfghj-np-tvwxz]{4}) # lookahead: followed by something and 4 consonants
^
(?>                         # open an atomic group
    [^c]++                  # all that is not a "c"
  |                         # OR
    c(?!hr)                 # "c" not followed by "hr" (negative lookahead)
)+                          # repeat the group one or more times (possessive)
$                           # end of the string anchor
~is