PHP - preg_match_all - 有点高兴

时间:2015-06-27 09:50:38

标签: php regex preg-match preg-match-all

我需要在字符串中找到文本的特定部分。 该文本需要:

  • 12个字符(仅限字母和数字)
  • 整个字符串必须至少包含3位数字
  • 带空格的3 * 4个字符(例如this
  • 上述示例中的每个块必须包含至少1个数字
  • linespodpreg_match_all("/(?<!\S)(?i:[a-z\d]{4}|[a-z\d]{12})(?!\S)/", $input_lines, $output_array);等词语不应被识别

enter image description here

所以我结束了这段代码:

preg_repace 但它不适用于所有要求。当然我可以使用str_replacepreg_match_all并删除所有(!,?,#)和循环计数数字,如果有4个或更多,但我想知道是否可以使用{{ 1}} ...

这是一个要搜索的字符串:

?K9X6 6GM6 LM11  // not recognized - but it should be
!K9X6 6GM6 LM11  // not recognized - but it should be
K0X6 0GM7 LM12! // not recognized - but it should be
K1X6 1GM8 LM13@ // not recognized - but it should be
K2X6 2GM9 LM14? // not recognized - but it should be
K3X6 3GM0 LM15# // not recognized - but it should be
K4X6 4GM1 LM16* // not recognized - but it should be
K5X65GM2LM17
bla bla bla
this shouldn't be visible
spod also shouldn't be visible
but line below should be!!
K9X66GM6LM11! (see that "!" at the end? Help me with this)

正确preg_match_all应该返回:

K9X6
6GM6
LM11
K9X6
6GM6
LM11
K0X6
0GM7
LM12
K1X6
1GM8
LM13
K2X6
2GM9
LM14
K3X6
3GM0
LM15
K4X6
4GM1
LM16
K5X65GM2LM17
K9X66GM6LM11

工作示例:http://www.phpliveregex.com/p/bHX

1 个答案:

答案 0 :(得分:2)

以下应该可以解决问题:

\b(?:(?=.{0,3}?\d)[A-Za-z\d]{4}\s??){3}\b

Demo

  • [A-Za-z\d]{4}匹配4个字母/数字
  • (?=.{0,3}?\d)检查这4个字符中的数字
  • \s??匹配空白字符,但尽可能尝试不匹配
  • \b确保所有内容都不包含在更大的单词中

请注意,这会允许K2X6 2GM9LM14之类的字符串,我不确定您是否希望这些字符串匹配。