Currently I have the following regular expression that matches 8 digits alphanumeric, I want to modify it such that it has to start with the number 2 and contains at least 2 numbers in this 8 digit. How can I do so?
preg_match('/[A-Za-z0-9]{8}/', $bio)
How about:
/^(?=2.*\d)[a-zA-Z0-9]{8}$/
if the number 2
counts for one of the 2 required number.
/^(?=2.*\d.*\d)[a-zA-Z0-9]{8}$/
if the number 2
doesn't count for one of the 2 required number.
explanation:
The regular expression:
(?-imsx:^(?=2.*\d)[a-zA-Z0-9]{8}$)
matches as follows:
NODE EXPLANATION
----------------------------------------------------------------------
(?-imsx: group, but do not capture (case-sensitive)
(with ^ and $ matching normally) (with . not
matching
) (matching whitespace and #
normally):
----------------------------------------------------------------------
^ the beginning of the string
----------------------------------------------------------------------
(?= look ahead to see if there is:
----------------------------------------------------------------------
2 '2'
----------------------------------------------------------------------
.* any character except
(0 or more times
(matching the most amount possible))
----------------------------------------------------------------------
\d digits (0-9)
----------------------------------------------------------------------
) end of look-ahead
----------------------------------------------------------------------
[a-zA-Z0-9]{8} any character of: 'a' to 'z', 'A' to 'Z',
'0' to '9' (8 times)
----------------------------------------------------------------------
$ before an optional
, and the end of the
string
----------------------------------------------------------------------
) end of grouping
----------------------------------------------------------------------
It's easy to make it start with 2, just add it at the beginning:
preg_match('/2[A-Za-z0-9]{7}/', $bio)
However regular expressions are not good for the second requirement - to make sure there are at least 2 digits. You could devise a regex that would check for two digits inside, but that won't be able to check the length to be 8. So you either make two separate regexes (one for length and one for 2 digits) or analyze the input in code separately character by character.