PHP - preg_match_all - 有点高级

PHP - preg_match_all - a little advenced

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

所以我以这段代码结束:

preg_match_all("/(?<!\S)(?i:[a-z\d]{4}|[a-z\d]{12})(?!\S)/", $input_lines, $output_array); 但它不适用于所有要求。当然,我可以使用 preg_repacestr_replace 并删除所有 (!,?,#) 并在循环中计数数字(如果有 4 个或更多)但我想知道是否可以使用 preg_match_all...

这里是要搜索的字符串:

?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 应该 returns 这个:

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

以下应该可以解决问题:

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

Demo

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

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