Weird regular expression problem

I have a funny problem with a regular expression that I can’t seem to fix. The expression is:


As you can see it is only ment to allow numbers, letters, commas, full stops and white space.

When I use this expression in preg_match() with a string it will return true even if I put in a dollar sign or a bracket or anything in the string but then when I put in two or more characters that are not allowed into the string it returns false.

How do I make the expression so that preg_match will return false if even one character that is not ment to be in the string is in the string? Thanks.

I’m gonna take a stab at this and say that the . is being translated as “any character”, and should be escaped as \.

That said, i’ve been known to be wrong about regex before.

. inside a character class () means . rather than a wildcard, so that is OK.

What that regular expression translates as to me is:

String contains:

  • Any character that isn’t a-z, A-Z, 0-9, ‘,’ or ‘.’
  • Followed by any character that isn’t ‘w’

The {1} is redundant, that is the default if you like.

If you want to only allow those characters, I’d use something like:


If you want to allow an empty string as well, substitute + for *

  1. a-zA-Z0-9,.\s ↩︎

Alright cool it seems to be working now. It work’s without the + at the end and the $ and the ^. Are they not neccessary so? Thanks.

  1. a-zA-Z0-9,.\s ↩︎

If you remove the + then it will only work for strings of 1 character. If you remove the $ it will check the first characters, but allow invalid ones afterwards. Removing ^ will allow invalid characters at the start. I put them all in there for a reason!

I just tried it there with no ^ at the start, no $ at the end and no + and it still does not allow me to add in unwanted characters at the start or the end and the string is on average about 20 characters.

All that will check if you remove all that is that the string contains at least 1 valid character