Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - preg_match()

Alright, so I want the user to be able to enter every character from A-Z and every number from 0-9, but I don't want them entering "special characters".

Code:

if (preg_match("/^[a-zA-Z0-9]$/", $user_name)) {
    #Stuff
}

How is it possible for it to check all of the characters given, and then check if those were matched? I've tried preg_match_all(), but I didn't honestly understand much of it.

Like if a user entered "FaiL65Mal", I want it to allow it and move on. But if they enter "Fail{]^7(,", I want it to appear with an error.

like image 706
MySQL Avatar asked Mar 28 '12 23:03

MySQL


People also ask

What is the use of Preg_match in PHP?

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

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 .

What does Preg_match_all return?

The preg_match_all() function returns the number of matches of a pattern that were found in a string and populates a variable with the matches that were found.

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.


2 Answers

You just need a quantifier in your regex:

Zero or more characters *:

/^[a-zA-Z0-9]*$/

One or more characters +:

/^[a-zA-Z0-9]+$/

Your regex as is will only match a string with exactly one character that is either a letter or number. You want one of the above options for zero or more or one or more, depending on if you want to allow or reject the empty string.

like image 65
Paul Avatar answered Oct 01 '22 02:10

Paul


Your regular expression needs to be changed to

/^[a-zA-Z0-9]{1,8}$/

For usernames between 1 and 8 characters. Just adjust the 8 to the appropriate number and perhaps the 1.

Currently your expression matches one character

like image 41
Ed Heal Avatar answered Oct 01 '22 01:10

Ed Heal