0

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?

Dharman
  • 30,962
  • 25
  • 85
  • 135
Coilerz
  • 61
  • 1
  • 6
  • Your question is too broad. Please point out any problems or challenges you are facing with this. – AKS May 23 '16 at 06:13
  • @AKS Basically will my regex only allow A-Z both upper and lowercase, numbers, dashes, and underscores. I just started working with regex a few days ago so I'm still very uncertain of how to do stuff with them. – Coilerz May 23 '16 at 06:16
  • Why would one want to limit user account names in that a narrow manner? – arkascha May 23 '16 at 06:16
  • Not account names, usernames. I don't want my users to have names like "@Bob&Joe*youtube" – Coilerz May 23 '16 at 06:19

2 Answers2

5

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'])
rock321987
  • 10,942
  • 1
  • 30
  • 43
  • Could you give me an example in terms of `preg_match`? I'm still very uncertain about the slashes at the end and beginning. – Coilerz May 23 '16 at 06:18
  • @Coilerz updated..you can use if condition with `preg_match`.`/` is just for denoting what exists between `/../` to be treated as regex – rock321987 May 23 '16 at 06:21
-1

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";

}

Yogesh Singasane
  • 283
  • 3
  • 12