0

Possible Duplicate:
regular expression for letters, numbers and - _

I would like to return true if the $var only includes (A-Z, a-z, 0-9 and -)

Something like: (this preg_match is to check if $var is mail, but I need the above)

if (!preg_match("/^[-!#$%&\'*+\\.\/0-9=?A-Z^_`{|}~]+@([-0-9A-Z]+\.)+([0-9A-Z]){2,4}$/i", $var))
    return false;
return true;

Any ideas? Im new with preg_match.

Community
  • 1
  • 1
Marko Livendo
  • 97
  • 3
  • 9
  • Is this an email address? if so dont use a regular expression to check email addresses use the php filters. looks like email but only includes (A-Z, a-z, 0-9 and -) is weird –  Oct 25 '12 at 21:23

1 Answers1

2

You need to use this preg_match with the code you provided:

preg_match("/^[A-Z0-9-]+$/i", $var)

It will match if $var includes only (A-Z, a-z, 0-9 and -) and is at least 1 character long. If you want to match also empty strings turn the + in a *.

enrico.bacis
  • 27,413
  • 7
  • 76
  • 108