Link to home
Start Free TrialLog in
Avatar of thepadders
thepadders

asked on

Non alphanumeric regex - easy!

I have a simple regex question, I just want to know if a string contains any characters other than a-z, 0-9 and - and _

I tried this:

      if (preg_match("/[^A-Z0-9_-]/", $_REQUEST['name'])) {
            echo "here";
      }

but that is not right. What am I doing wrong?
Avatar of Diablo84
Diablo84

hi thepadders,

try this pattern: "/^[A-Z0-9_-]+$/"

     if (preg_match("/^[A-Z0-9_-]+$/", $_REQUEST['name'])) {
          echo "here";
     }

bear in mind it is case sensitive
SOLUTION
Avatar of Diablo84
Diablo84

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
This page may be useful to you: http://us2.php.net/manual/en/reference.pcre.pattern.syntax.php

Pattern syntax. Note in the above i have used:

\w =  any "word" character
\d =  any decimal digit
ASKER CERTIFIED SOLUTION
Avatar of Zvonko
Zvonko
Flag of North Macedonia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
good point about \w, it of course covers _ too

although your pattern does not match with a test, so perhaps the pattern: "/^[\w\-]+$/"
Zvonko,

a '-' placed at the start or end of a character class [square braces] does not need escaping, only when it is surrounded by other characters :)

But that's as good as it gets

_Blue
Diablo, what you recommend, matches to strings that ALL THEIR CHARACTERS are something other than alphanumberic and dash.
The pattern he looks for is /[^\w-]/.  Just that.
Avatar of thepadders

ASKER

Thank you everyone, mces had the best answer is    

 if (preg_match("/[^\w\-]/", $_REQUEST['name'])) {
          echo "here";
    }

I have split the points as it was a progression to that answer. Thanks everyone.
You are welcome.