0

I have a preg_match statement like so:

preg_match("/^[0-9a-zA-z\.\_\-]$/", $_POST['username'])

But it always equates to false.

"aaa" - false
"#$&Y#" - false
"   a#*$7"- false

WHY

4
  • Is your input actually as such -- ie, surrounded with double quotes? If yes, no wonder it fails Commented Jan 15, 2012 at 2:47
  • Also, no need to escape the dot, underscore or dash (since you are putting it at the end) here: [0-9a-zA-Z._-] Commented Jan 15, 2012 at 2:48
  • @fge Not true. Look at Rich Adams' answer. It works. Commented Jan 15, 2012 at 2:50
  • if you talk about ._-, true -- try it and see Commented Jan 15, 2012 at 2:51

1 Answer 1

5

It's only matching one character, you need a + so that it matches one or more.

preg_match("/^[0-9a-zA-z\.\_\-]+$/", $_POST['username'])
Sign up to request clarification or add additional context in comments.

1 Comment

Also note A-z -- and that ., _ and - need not be escaped

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.