Coilerz Coilerz - 1 year ago 81
PHP Question

PHP Regular expression for only allowing alphanumeric, dashes, underscores

I'm very new to using regular expressions and am trying to allow only

A-Z, a-z, 0-9, -, _

I'm using the following expression which is working:

preg_match('/^[a-zA-Z0-9-_]+$/i', $_POST['sign_up_username'])

My question is if this is the correct way to go about doing this. I'm not sure if this is the right place to post this. Any help would be great. Thanks.

Answer Source

The regex is incorrect. Move - in last or beginning or escape it in character class because - have special meaning inside character class. It denotes range within character class. You can use



\w = [a-zA-Z0-9_]

So, you can use


Also, there is no need of i modifier and finally yes it will allow only A-Z both upper and lowercase, numbers, dashes, and underscores

This will suffice in PHP

preg_match('/^[\w-]+$/', $_POST['sign_up_username'])