# Preg_match pattern for user input filtering

My users may need to supply a 'disease category' to my site. I need to let them use all alphanumeric characters, hyphens and single quotes. Would someone review this to see if they feel it's reasonable safe? I'm very happy for suggestions to make it tighter,

      $disease_category = "some user input";$reg = "#[^'a-z0-9\s-]#i";
preg_match($reg,$disease_category);

• I don't think you've asked a good, clear question. The code doesn't really make sense ($disease_category vs. $new_category, the unexplained \s in the regex, and the discarding of the result of preg_match()). Also, "safe" is nebulous term, since it all depends on what you intend to do with the string. – 200_success Jun 23 '14 at 5:50
• I have edited the $new_caetgory which should be$disease_category. I disagree with the clarity bit though - I think the question is very clear - I want the preg_match to match all alphanumeric characters, hyphens and single quotes. Nothing else. As I am new to regex, and this is really my first attempt to construct the correct pattern, I wanted to get some expert feed back on whether my pattern serves the purpose required. – GhostRider Jun 23 '14 at 10:58
• Many thanks to Madara and 200_success who have schooled me in the difference between validation and security. – GhostRider Jun 23 '14 at 13:16

Well if having an underscore in your line could be acceptable, then

$reg = "#[^\w\s-']#i";  could be used. If you cannot have underscores, then $reg = "#[^a-z\d\s-']#i";


could be correct.

A conditional using preg_match would be safe with this.

• The - should be the first, or last part of a regex character class section [...]. It otherwise needs to be escaped, or it becomes a range indicator. – rolfl Jun 21 '14 at 14:07
• Update ... actually, this will work, but in general, the meaning of the - in a regex is complicated, and the internal use of - as a non-range character is ... unexpected, for me at least. – rolfl Jun 21 '14 at 14:18
• @rolfl Regex101.com comes in handy! I hadn't thought of the confusion you pointed out, in future cases I'll make sure order them in a more clear way – Alex L Jun 21 '14 at 20:48
• Why not start now? :) – Jack Jun 23 '14 at 11:28