Why does my RegExp return false with proper number of characters?
$gi = filter_var(filter_var($_POST['group_id'], FILTER_SANITIZE_STRING),
FILTER_VALIDATE_REGEXP, array(
"options"=>array("regexp"=>"/^[a-zA-Z0-9_](?=[^\s]+$).{5,20}$/")));
That is the code I'm using. This is a PHP & MySQL application. The problem is that it is returning FALSE with anything 5 characters or shorter. If I change the '5' to a '6', then anything 6 characters or shorter returns FALSE. Why is this?
Also, the following code behaves the same:
$gi = filter_var($_POST['group_id'], FILTER_VALIDATE_REGEXP,
array("options"=>array(
"regexp"=>"/^[a-zA-Z0-9_](?=[^\s]+$).{5,20}$/")));
I'm under the impression that my regexp is 1) limiting entries to letters, numbers, and underscores, 2) prohi开发者_运维知识库biting whitespace, and 3) requiring atleast 5 characters and setting a maximum of 20 characters.
Your regex:
/^[a-zA-Z0-9_](?=[^\s]+$).{5,20}
is matching 5 characters, but only after it matches 1 character within [a-zA-Z0-9_]
, and then on to the 5 characters. So at minimum you need a 6 character string to match.
Based on your last paragraph, something like the following is more to what you're looking for:
/^[0-9a-zA-Z_]{5,20}$/
EDIT: Corrected thanks to @Allan, not quite in to the cognitive thinking pattern yet, coffee deprivation. ;-)
/.{5,20}/
This piece of RegEx is responsible as you are asking the engine to match AT LEAST 5 characters (Any characters) and 20 characters if max. Fix that piece accordingly.
Hope it helps :)
EDIT: Sorry, didnt read the last part of the question.
1) Wrong. The ^ operator negates whatever is in front, so the first char CAN NOT be any letter, any number nor underscore [Replace that with /^[\w_]/
if you really want that overkill filtering]
2) Right. There cannot be whitespaces before that end of line.
3) Pretty much whats above the EDIT ;)
For more regex info go to http://regular-expressions.info
精彩评论