Using regex to filter strings by length
I am trying to validate a input field with regex with this pattern [A-Z开发者_StackOverflowa-z]{,10}
I want it to only find a match if 10 or less chars was sent in the input field, the problem I get is that it will match all words that is less then 10 chars.
Is there a way to say if there is more then 10 chars in the input field come back as false, or is it just better to do a strlen
with php?
If you need to validate that it's alphabetic only, don't use strlen()
. Instead, put boundaries (^$
) on your regex:
/^[A-Za-z]{,10}$/
There is an important syntax mistake being made here by the OP and all the current regex answers: When using the curly brace quantifier with PHP (PCRE), you need to specify the first number. (i.e. The expression: {,10}
is NOT a valid quantifier!) Although the comma and second number are optional, the first number in a curly brace quantifier is required. Thus the expression should be specified like so:
if (preg_match('/^[A-Za-z]{0,10}$/', $text))
// Valid input
else
// Invalid input
If you just match ^[A-Za-z]{,10}$
it will check that the whole string is 10 or less.
^[A-Za-z]{,10}$
$@#$^&$a36#&$^
will pass your regexp because a
is substring of it and a
pass [A-Za-z]{,10}
If you are only interested in the length of the string, regex is heavy-handed and you should use strlen
instead.
精彩评论