Regular expression that accepts letters, numbers, and underline

3

How do I get the ER below to accept letters, numbers, and underline, and continue not allowing other characters?

preg_match('/[^a-z\d]/', $_POST['login'])
    
asked by anonymous 21.08.2018 / 03:14

1 answer

2

Brackets ( [] ) define a character class , that is, accept everything inside their. Ex: [ab] means "the letter a or the letter b ".

But when the first character inside the brackets is ^ , you're denying what's inside it. Ex: [^ab] means "anything other than a nor b ".

So, by doing [^a-z\d] , you're rejecting lowercase letters and digits. To accept letters, numbers, and underlines, you must include them in the brackets and remove the ^ , then it would be [A-Za-z0-9_] .

I'm assuming you want to accept strings with more than one character, so use the + quantizer, which means "one or more occurrences." Then the expression is [A-Za-z0-9_]+ .

Since these are the only allowed characters, also use ^ out of the brackets and at the beginning of the expression, since it means the start of the string, and at the end put $ , which means the end of the string. The complete expression is:

preg_match("/^[A-Za-z0-9_]+$/", $_POST['login'])

That is: one or more occurrences ( + ) of letters, numbers or underline ( [A-Za-z0-9_] ), from the beginning ( ^ ) to the end ( $ ) of the string.

    
21.08.2018 / 03:36