-2

I need an regex to my preg_match(), it should preg (allow) the following characters:

String can contain only letters, numbers, and the following punctuation marks:

  • full stop (.)
  • comma (,)
  • dash (-)
  • underscore (_)

I have no idea , how it can be done on regex, but I think there is a way!

sidyll
  • 57,726
  • 14
  • 108
  • 151
Cyclone
  • 14,839
  • 23
  • 82
  • 114
  • 4
    If only there was a way to find out more on preg syntax.. :P – Rijk Oct 18 '11 at 12:42
  • Yes, this can be done. See the manual on http://www.php.net/manual/en/regexp.reference.character-classes.php or some of the tools http://stackoverflow.com/questions/32282/regex-testing-tools – mario Oct 18 '11 at 12:43
  • 2
    Look what I found: http://www.regular-expressions.info/ – Felix Kling Oct 18 '11 at 12:44

1 Answers1

2
^[\p{L}\p{N}.,_-]*$

will match a string that contains only (Unicode) letters, digits or the "special characters" you mentioned. [...] is a character class, meaning "one of the characters contained here". You'll need to use the /u Unicode modifier for this to work:

preg_match(`/^[\p{L}\p{N}.,_-]*$/u', $mystring);

If you only care about ASCII letters, it's easier:

^[\w.,-]*$

or, in PHP:

preg_match(`/^[\w.,-]*$/', $mystring);
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561