I 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'])
Is this the correct way to go about doing this?
I 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'])
Is this the correct way to go about doing this?
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
^[-a-zA-Z0-9_]+$
Also
\w = [a-zA-Z0-9_]
So, you can use
^[\w-]+$
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'])
if(preg_match('/^[a-zA-Z0-9-_]+$/i', $str) == 1)
{
// string only contain the a to z , A to Z, 0 to 9, -_
echo "yes";
}
else
{
echo " no";
}