I’m trying to learn how to use preg_match. I want users to be only allowed to sign up with username between 2-20 characters which can contain a-zA-Z0-9.
Now the tricky part where Im getting lost, I want them to be able to include one hyphen anywhere in the username so,
-Brad = TRUE --Brad = FALSE B-Rad = TRUE
You can build this up step-by-step. You want a username that consist of 2-20 specific characters:
Now you want to allow a single
-character somewhere in there (the trick part):The
-character is only allowed if it is not followed up by another-to the end of the string:This is a so called Lookahead assertion. Combined with an alternation, the regex completes to:
Compared to the other answers given, this one respects your length specification.