Jensen Jensen - 5 months ago 23x
PHP Question

Regex allowing spaces (for a Phone number regex)

I have this regex:

preg_match("#^([0-9]+)$#", $post['telephone'])

who allow only numbers (for a phone number in the French type so 0123456789) but I would like to allow spaces. For example allow this type of string: "01 23 45 67 89".

Can you please help me?


If it is OK to have spaces anywhere in your string then it is simple, just add it to your character class

preg_match("#^([0-9 ]+)$#", $post['telephone'])

but this will allow 5 spaces in the beginning.

^\d{2}(?: ?\d+)*$

would be a bit more sophisticated. Starts with two digits, then a optional group starting with an optional space followed by at least 1 digit. this group can be repeated 0 or more times.

This would match

01 23 45 67 89


01234 5679