douzhu6149 2015-06-27 09:50
浏览 45
已采纳

PHP - preg_match_all - 有点高级

I need to find specific part of text in string. That text need to have:

  • 12 characters (letters and numbers only)
  • whole string must contains at least 3 digits
  • 3*4 characters with spaces (ex. K9X6 6GM6 LM11)
  • every block from example above must contains at least 1 number
  • words like this, line, spod shouldn't be recognized

enter image description here

So I ended with this code:

preg_match_all("/(?<!\S)(?i:[a-z\d]{4}|[a-z\d]{12})(?!\S)/", $input_lines, $output_array); But it won't works for all of requirements. Of course I can use preg_repace or str_replace and remove all (!,?,#) and in a loop count numbers if there are 4 or more but I wonder if it is possible to do with preg_match_all...

Here is a string to search in:

?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)

Correct preg_match_all should returns this:

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

working example: http://www.phpliveregex.com/p/bHX

  • 写回答

1条回答 默认 最新

  • douhua1890 2015-06-27 12:08
    关注

    The following should do the trick:

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

    Demo

    • [A-Za-z\d]{4} matches 4 letters/digits
    • (?=.{0,3}?\d) checks there's a digit in these 4 characters
    • \s?? matches a whitespace character, but tries not to match it if possible
    • \b makes sure everything isn't contained in a larger word

    Note that this will allow strings like K2X6 2GM9LM14, I'm not sure whether you want these to match or not.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵