1

I want a regex for PHP that can match two alphabetic characters or two numeric characters. For example:

AB or 45

The characters can't be mixed with alphabetic and numeric.

^(\w)\1|[A-Z|0-9]{2}$

I used the above regex but it doesn't work correctly.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563

1 Answers1

1

You may use

preg_match('~^(?:[A-Za-z]{2}|\d{2})$~', $s, $match)

The ^(?:[A-Za-z]{2}|\d{2})$ pattern matches two ASCII letters or two ASCII digits.

See the regex demo and the regex graph:

enter image description here

Details

  • ^ - start of string
  • (?:[A-Za-z]{2}|\d{2}) - a non-capturing group matching either
    • [A-Za-z]{2} - two ASCII letters
    • | - or
    • \d{2} - two digits
  • $ - end of string.

To make it match all Unicode letters, you may use

preg_match('~^(?:\p{L}{2}|[0-9]{2})$~u', $s, $match)
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563