Reputation: 89
I have the following preg_match statement that allows an input to be either letters a to z and numbers 0 to 9 only and it must be between 5 and 30 characters in length.
However, how would I also make sure that the input is not all numerics? For example it must contain at least 1 a to z letter?
if (preg_match ('/^[a-zA-Z0-9\'.]{5,30}$/i', $str['user'])) {
}
Upvotes: 2
Views: 767
Reputation: 626738
You wrote you have a regex that allows an input to be either letters a to z and numbers 0 to 9 only, but actually ^[a-zA-Z0-9\'.]{5,30}$
matches a string of 5 to 30 ASCII letters, digits and also '
or .
.
If you just want to make your regex match what it matches, but not a string that only consists of digits, use a (?!\d+$)
lookahead:
'/^(?!\d+$)[a-z0-9\'.]{5,30}$/i'
^^^^^^^^
Note you do not need to specify the A-Z
or a-z
range if you use a i
case insensitive flag (just either of them is enough).
The (?!\d+$)
is a negative lookahead that fails the match if there are one or more digits followed by the end of string ($
) immediately to the right of the current location (which is the start of the string).
See the regex demo.
If you do not want to match a string that only consists of dots, or '
, or digits, use
'/^(?!(?:\d+|([\'.])\1*)$)[a-z0-9\'.]{5,30}$/i'
See another demo.
Upvotes: 3