Search code examples
phpregexpreg-match

Validating specific syntax with preg_match


I've come up with the code below after going thru examples and documents on web about regular expressions however it doesn't work as expected. So based on requirement below, only 'ABCDEF05', 'A21 and 'C99' should be validated.

Requirement:

  • First part of the string can be; Min 1 Max 6 char long. Upper case only.
  • Second part of the string can be; Exactly 2 chars long but 00 is not accepted.
  • So all together: It can be min 3 max 8 chars long.

TEST:

$arr = array('d12', '1', 'A123', 'A1234', 'AB00', 'ABCDEFG01', 'ABCDEF00', 'ABCDEF05', 'A21', 'C99');

foreach ($arr as &$key) {
   if (preg_match('/^([A-Z]{1,6})([1-9][0-9]{2})/', $key)) {
      echo "$key\n";
   }
}

Solution

  • Use negative lookahead:

    if (preg_match('/^([A-Z]{1,6})(?!00)(\d\d)$/', $key)) {