Does anybody know using regular expression with preg_match how can I allow in a string only numbers, hyphens(-) and spaces?
Is that expression good enough?
preg_match('/[^a-z\s-]/i', $_POST['phone'])
No, it's not good enough because you assume that there is only latin letters, white characters and hyphen in the world!
The simpliest way is to write what you need (instead of what you don't need):
preg_match('/^[0-9- ]+$/D', $_POST['phone']);
or
preg_match('/^[0-9-\s]+$/D', $_POST['phone']); // for any kind of white spaces
Note the quantifier +
to repeat the character class and the anchors (^
for start and $
for end) to ensure that the string is checked from start until the end. The D
modifier avoids to have a newline at the end (it gives the $
anchor a strict meaning, otherwise $
can match the end of the string just before a last newline (a strange behaviour isn't it?)).