How do I make a regex that enforces:
when using a php preg_match?
Here's what I got:
^[A-Za-z0-9]{10,50}$
It seems to do everything except enforce letters AND numbers.
By combining the interval quantifier with the surrounding start- and end-of-string anchors, the regex will fail to match if the subject text's length falls outside the desired range.
The Match-zero-or-more Operator ( * ) This operator repeats the smallest possible preceding regular expression as many times as necessary (including zero) to match the pattern. `*' represents this operator. For example, `o*' matches any string made up of zero or more `o' s.
\d is a digit (a character in the range [0-9] ), and + means one or more times. Thus, \d+ means match one or more digits. For example, the string "42" is matched by the pattern \d+ .
Do:
^(?=.*(?:[A-Za-z].*\d|\d.*[A-Za-z]))[A-Za-z0-9]{10,50}$
(?=.*(?:[A-Za-z].*\d|\d.*[A-Za-z]))
is zero width positive lookahead, this makes sure there is at least one letter, and one digit present
[A-Za-z0-9]{10,50}
makes sure the match only contains letters and digits
Demo
Or even cleaner, use two lookaheads instead of OR-ing (thanks to chris85):
^(?=.*[A-Za-z])(?=.*\d)[A-Za-z0-9]{10,50}$
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With