I need a regex to accept only strings that contain both alphabetic and numeric characters. For example:
ABCDEF: wrong
123456: wrong
!##$%@.: wrong
ABCD123!@$: wrong
ABC12389IKEIIJ29: **correct**
How can I do it with PHP?
I need a regex to accept only strings that contain both alphabetic and numeric characters. For example:
ABCDEF: wrong
123456: wrong
!##$%@.: wrong
ABCD123!@$: wrong
ABC12389IKEIIJ29: **correct**
How can I do it with PHP?
preg_match('/^[0-9A-Z]*([0-9][A-Z]|[A-Z][0-9])[0-9A-Z]*$/', $subject);
If you want to allow small and capital letters, add an i
at the end of the pattern string.
Explanation:
[0-9][A-Z]
matches one digit followed by one capital letter
[A-Z][0-9]
matches one capital letter followed by one digit
([0-9][A-Z]|[A-Z][0-9])
matches one of these two sequences
[0-9A-Z]*
matches 0-n digits and/or capital letters
The idea is: A string which contains both (and only), letters and numbers, has at least one subsequence where a letter follows a digit or a digit follows a letter. All the other characters (preceding and following) have to be digits or letters.