dongyu9667 2015-02-04 14:18
浏览 39
已采纳

使用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
";
   }
}
  • 写回答

1条回答 默认 最新

  • dongzhanlu8890 2015-02-04 14:57
    关注

    Use negative lookahead:

    if (preg_match('/^([A-Z]{1,6})(?!00)(\d\d)$/', $key)) {
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?