preg_match() and username

Karem picture Karem · Jul 31, 2010 · Viewed 13.2k times · Source
function isUserID($username) {
  if (preg_match('/^[a-z\d_]{2,20}$/i', $username)) {
    return true;
  } else {
    return false;
  }
}   

Easy one.., i have this, can you explain what it checks for? I know it checks if the username have length between 2-20, what more? Thanks

Answer

Dagg Nabbit picture Dagg Nabbit · Jul 31, 2010

It searches for text containing only alphanumeric and underscore characters, from 2 to 20 characters long.

/^[a-z\d_]{2,20}$/i
||||  | |||     |||
||||  | |||     ||i : case insensitive
||||  | |||     |/ : end of regex
||||  | |||     $ : end of text
||||  | ||{2,20} : repeated 2 to 20 times
||||  | |] : end character group
||||  | _ : underscore
||||  \d : any digit
|||a-z: 'a' through 'z'
||[ : start character group
|^ : beginning of text
/ : regex start