I've been reading and reading on regular expressions, but I can't figure out what's wrong with my code:
开发者_运维问答if(eregi("^[A-Za-z0-9_\-]$", $username)){return true;}
It never returns true. I'm trying to validate usernames and only allow lowercase a-z, uppercase a-z, numbers, hyphens and underscores.
eregi() is deprecated. Use preg_match() instead.
You have no regex delimiters (such as /, @, ~, etc).
Use preg_match('/^[\w-]+\z/').
/is the delimiter I have used. PHP allows you to use many other characters.\wis a shortcut to[A-Za-z0-9_]. It is useful here to make the regex shorter and hopefully clearer.- Inside of a character class, if the
-is not part of a valid range, it will be taken literally. I have not escaped it because it does not required being escaped in this scenario. +is a quantifier that says match 1 or more times. You need that here.\zmeans match end of string. You used$, which will allow a trailing\n.
Don't use eregi - it is deprecated, use preg_match instead:
if (preg_match("/^[A-Za-z0-9_\-]+/i$", $username)){return true;}
加载中,请稍侯......
精彩评论