I need to filter out strings that contain anything other than letters, numbers, dots, hyphens, apostrophes or spaces.
Strings with letters, numbers, dots, hyphens and spaces pass the test, but when they contain an apostrophe it fails. (The escape characters on the dot and hyphen don’t seem to be making any difference so I put them in just to be sure)
Any thoughts on this?
if (preg_match("/[^a-zA-Z0-9\.\-\'\\s]/", $some_var)){
echo "Invalid characters";
}
Your answer doesn’t compile due to the escaping of some of the characters (escaped as being part of a string, before passed into the preg_match function).
You could try double escaping:
but escaping dot, hyphen and apostrophe is not needed, so you can simplify:
Note that the hyphen is moved to the end, so that it’s not mistaken for a character range. Personally, I prefer to escape it to prevent other developers accidentally adding new characters to the end of the list and causing unexpected behaviour.
So:
Finally, you may want to check your input (the
$some_varvariable) – does this actually contain a backslash as PHP sometimes will add this in (eg. user types “can’t”, but gets sent through as “can\’t” – you may need tostripslashesfirst).Eg.