How to use `preg_match ()` to match username
I'm trying to validate usernames in PHP with preg_match()
, but I can't seem to get it to work the way I want it to. I need preg_match()
:
- only accept letters or numbers at the beginning and end of a string
- accept periods, dashes, underscores, letters, numbers
- must be between 5 and 20 characters long
preg_match('/^[a-zA-Z0-9]+[.-_]*[a-zA-Z0-9]{5,20}$/', $username)
+3
source to share
3 answers
Divide the requirements into smaller chunks and you will see that it becomes much easier:
- The first character must be 1 letter or number
- Middle characters must be period, underscore, letter or number.
- The last character must be a letter or number.
- Since the first and last segments should be 1 character, the middle should be between 3 and 18
~^[a-z0-9]{1}[a-z0-9._-]{3,18}[a-z0-9]{1}$~i
+6
source to share