PHP - preg_match_all - listened a bit

I need to find a specific piece of text in a string. This text should have:

  • 12 characters (letters and numbers only)
  • the whole line must contain at least 3 digits
  • 3 * 4 characters with spaces (e.g. K9X6 6GM6 LM11 )
  • each block from the above example must contain at least 1 number
  • words like this , line , spod should not be recognized

enter image description here

So, I ended up with this code:

preg_match_all("/(?<!\S)(?i:[az\d]{4}|[az\d]{12})(?!\S)/", $input_lines, $output_array); But it will not work for all requirements. Of course, I can use preg_repace or str_replace and delete all (!,?, #) And the number of loops if there are 4 or more, but I wonder if it is possible to do this with preg_match_all ...

Here is the line 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) 

Correctly preg_match_all should return 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

+6
source share
1 answer

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 / numbers
  • (?=.{0,3}?\d) checks there the digit in these 4 characters
  • \s?? matches whitespace but tries not to match if possible
  • \b ensures that everything is not contained in a larger word

Please note that this will allow strings like K2X6 2GM9LM14 , I'm not sure if you want them to match or not.

+2
source

Source: https://habr.com/ru/post/989852/


All Articles