1

Read a ton, didn't see an answer. Sorry if this is a duplicate.

Running PHP 5.4.

I have a form that takes Contact Info (name, email, number, etc).

The regex I would like is: only allow letters, numbers, a space, a dash, a backslash, a colon, an @ sign, and a forward slash.

This is what I'm using (for all input values, only showing one below):

if (!preg_match("/^[./\\@\w\sa-zA-Z0-9:-]+$/", $_POST["Name"])

I keep getting unknown modifier error. I don't care if the above is fixed, or replaced with a different regex, i just need to allow only the things i mentioned earlier.

Thanks in advance.

Daniel
  • 107
  • 1
  • 9

2 Answers2

2

You need to escape /

This should be

^[.\/\\@\w\sa-zA-Z0-9-]+$

Test your regex pattern at regex101


  • \s match any white space character [\r\n\t\f ] If you are looking for space only the use

  • \w match any word character [a-zA-Z0-9_] that includes underscore as well. Just remove it from your regex pattern


only allow letters, numbers, a space, a dash, a backslash, a colon, an @ sign, and a forward slash.

It should be ^[0-9a-zA-Z \\:@\/-]+$

Note: Make sure hyphen - must be in the beginning or ending of the Character class or should be escaped because hyphen has special meaning in Character class to define a range.

Braj
  • 46,415
  • 5
  • 60
  • 76
1

You can use:

if (!preg_match('~^[./\\\@\w\s:-]+$~', $_POST["Name"])

i.e. use an alternate delimiter like ~, other than / since your regex is also using / in it.

I have also remove [a-zA-Z0-9] since you already have \w (word character) in your character class.

anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 1
    I marked the other guy as answer, since he replied first, but I really appreciate your additions. Thank you very much. – Daniel Aug 18 '14 at 11:54
  • 1
    By the way, I needed to escape the backslash one more time. So it's : '~^[./\\\@\w\s:-]+$~' – Daniel Aug 18 '14 at 12:18
  • 2
    Yes just noticed and updated for anyone accessing this thread in future. – anubhava Aug 18 '14 at 13:40