开发者

Eregi Validation Issue [duplicate]

This question already has answers here: How can I convert ereg expressions to preg in PHP? (4 answers) Closed 3 years ago.

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.
  • \w is 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.
  • \z means 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;}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜