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";
  • \$\begingroup\$ 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. \$\endgroup\$ – 200_success Jun 23 '14 at 5:50
  • \$\begingroup\$ 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. \$\endgroup\$ – GhostRider Jun 23 '14 at 10:58
  • 1
    \$\begingroup\$ Many thanks to Madara and 200_success who have schooled me in the difference between validation and security. \$\endgroup\$ – 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.

  • 2
    \$\begingroup\$ 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. \$\endgroup\$ – rolfl Jun 21 '14 at 14:07
  • \$\begingroup\$ 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. \$\endgroup\$ – rolfl Jun 21 '14 at 14:18
  • \$\begingroup\$ @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 \$\endgroup\$ – Alex L Jun 21 '14 at 20:48
  • \$\begingroup\$ Why not start now? :) \$\endgroup\$ – Jack Jun 23 '14 at 11:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.