1

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.

Jack
  • 203
  • 1
  • 4
  • 9

2 Answers2

5

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.
alex
  • 479,566
  • 201
  • 878
  • 984
1

Don't use eregi - it is deprecated, use preg_match instead:

if (preg_match("/^[A-Za-z0-9_\-]+/i$", $username)){return true;}
Nemoden
  • 8,816
  • 6
  • 41
  • 65
  • Why `i` pattern modifier and explicitly `A-Za-z` ? – alex Jul 13 '11 at 01:40
  • @alex `i` is for a case _insensitive_ search, which `eregi` does, and should be included. – Kevin Ji Jul 13 '11 at 03:40
  • @mc10: But the answer already covers `A-Za-z` in the character class. – alex Jul 13 '11 at 03:48
  • @alex, I've just copied the former regular expression. The main point in my answer is that the OP should not use `eregi` and I suppose @Jack would figure out the rest himself. – Nemoden Jul 14 '11 at 05:48