Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

preg_match() and username

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

like image 781
Karem Avatar asked Jul 31 '10 21:07

Karem


People also ask

What is Preg_match function?

Definition and Usage. The preg_match() function returns whether a match was found in a string.

What is the difference between Preg_match and Preg_match_all?

preg_match stops looking after the first match. preg_match_all , on the other hand, continues to look until it finishes processing the entire string. Once match is found, it uses the remainder of the string to try and apply another match.

What is the purpose of Preg_match () regular expression in PHP?

The preg_match() function will tell you whether a string contains matches of a pattern.

What value is return by Preg_match?

Return Values ¶ preg_match() returns 1 if the pattern matches given subject , 0 if it does not, or false on failure. This function may return Boolean false , but may also return a non-Boolean value which evaluates to false . Please read the section on Booleans for more information.


2 Answers

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
like image 82
Dagg Nabbit Avatar answered Sep 25 '22 11:09

Dagg Nabbit


/^[a-z\d_]{2,20}$/i

Splicing it up:

/ is the regex delimiter; you can choose anything you like, but a forward slash is the most common one.

^ means 'match beginning of input': The following expression must be at the beginning for the regex to match.

[a-z\d_] is a character class; it means 'any of the characters between the square brackets'; the backslash combined with the d is a shortcut for 'digits', and the dash indicates an inclusive range; thus, the character class says 'any letter or digit, or the underscore'.

{2;20} is a quantifier that says that the preceding expression (the character class) must be repeated 2 to 20 times.

$ means 'match end of input', similar to ^.

Another / terminates the regex itself; what follows are procession options, in this case i, which means 'case-insensitive'.

like image 43
tdammers Avatar answered Sep 22 '22 11:09

tdammers