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


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

.



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

      

+2


source


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

      

+2


source







All Articles