user1307016
user1307016

Reputation: 405

How to use `preg_match()` to match a username

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:

  1. accept only letters or numbers at the beginning and end of the string
  2. accept periods, dashes, underscores, letters, numbers
  3. must have a length between 5-20 characters

preg_match('/^[a-zA-Z0-9]+[.-_]*[a-zA-Z0-9]{5,20}$/', $username)

Upvotes: 3

Views: 4504

Answers (3)

alex
alex

Reputation: 490423

If the regex is confusing you, you could always match the characters with a regex and then explicitly check for the length of the string with strlen().

$valid = preg_match('/^[a-zA-Z\d]+[\w.-]*[a-zA-Z\d]$/', $username)
         AND strlen($username) >= 5 AND strlen($username) <= 20;

Upvotes: 2

Corbin
Corbin

Reputation: 33457

Break down the requirements into smaller pieces and you'll see that it becomes a lot easier:

  • The first character must be 1 letter or number
  • The middle characters must be a period, dash underscore, letter or number
  • The last character must be a a letter or number
  • As the first and last segments must be 1 character, the middle must be 3 to 18
~^[a-z0-9]{1}[a-z0-9._-]{3,18}[a-z0-9]{1}$~i

Upvotes: 6

Alix Axel
Alix Axel

Reputation: 154603

if (preg_match('~^[0-9a-z][-_.0-9a-z]{3,18}[0-9a-z]$~i', $username) > 0)
{
    // valid
}

Upvotes: 2

Related Questions