Konstantinos
Konstantinos

Reputation: 157

preg_match - can only consist of numbers, hyphens(-) and spaces

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'])

Upvotes: 2

Views: 6034

Answers (1)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89547

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?)).

Upvotes: 4

Related Questions