PHP - preg_match ()

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


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


How is it possible to check all provided characters and then check if they were matched? I tried preg_match_all()

it but I didn't really understand it.

As if the user entered "FaiL65Mal", I want him to allow it and go. But if they come in "Fail {] ^ 7 (," I want it to appear with an error.


source to share

3 answers

You just need a quantifier in your regex:

Zero or more characters *




One or more characters +




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



Your regex should be changed to



For usernames from 1 to 8 characters. Just tune 8 to the appropriate number and possibly 1.

Your expression currently matches one character



Please keep in mind preg_match()

that preg_match()

other functions preg_*()

are not reliable 0

either because they return or false

on failure, so a simple if will not throw an error.

Consider using T-Regx :

if (pattern(('^[a-zA-Z0-9]{1,8}$')->matches($input)) 
    // Matches! :)




All Articles