I’m trying to validate usernames in PHP using preg_match() but I can’t seem to get it working the way I want it. I require preg_match() to:
- accept only letters or numbers at the beginning and end of the string
- accept periods, dashes, underscores, letters, numbers
- must have a length between 5-20 characters
preg_match('/^[a-zA-Z0-9]+[.-_]*[a-zA-Z0-9]{5,20}$/', $username)
Break down the requirements into smaller pieces and you’ll see that it becomes a lot easier: