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:
^[a-zA-Z0-9]{2,20}$
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:
^(?:[a-zA-Z0-9]|[-](?=[^-]*$)){2,20}$
Compared to the other answers given, this one respects your length specification.
You could use preg_match with:
\w*-?\w*
It will ensure that one hyphen exists, but will also match just a hyphen. You can also use:
(\w*-?\w+)|(\w+-?\w*)
To avoid matching only a hyphen. Or you can check if the match has length > 1.
You said to be able to, so I assumed the hyphen isn't a requirement. If it is, remove the ? in the regex.
If you plan on matching in a sentence, you could use a word break (\b) with the \w+ part. If you're using this on a trimmed string then add ^ and $ to the start and end respectively to avoid matching --Bra-d
as true.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With