Search code examples
phpregexquantifiers

Regex validation pattern only allows one character


I'm trying to make functions for validating usernames, emails, and passwords and my regex isn't working. My regex for usernames is ^[a-zA-Z0-9 _-]$ and when I put anything through that should work it always returns false.

As I understand it, the ^ and $ at the beginning and the end means that it makes sure the entire string matches this regular expression, the a-z and A-Z allows all letters, 0-9 allows all numbers, and the last three characters (the space, underscore, and dash) allow the respective characters.

Why is my regular expression not evaluating properly?


Solution

  • You need a quantifier, + or *. As it was written that only allows 1 of the characters in the character class.

    Your a-zA-Z0-9_ also can be replaced with \w. Try:

    ^[\w -]+$
    

    + requires 1 or more matches. * requires 0 or more matches so if an empty string is valid use *.

    Additionally you could use \h in place of the space character if tabs are allowed. That is the metacharacter for a horizontal space. I find it easier to read than the literal space.

    Per comment, Update:

    Since it looks like you want the string to be between a certain number of characters we can get more specific with the regex. A range can be created with {x,y} which will replace the quantifier.

    ^[\w -]{3,30}$
    

    Additionally in PHP you must provide delimiters at the start and end of the regex.

    preg_match("/^[\w -]{3,30}$/", $username);
    

    Additionally, you should enable error reporting so you get these useful errors in the future. See https://stackoverflow.com/a/21429652/3783243