Set spaces regularly (to regularly express a phone number)

I have this regex:

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

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

Can you help me?

+3
source share
4 answers

If everything is ok to have spaces in any line, it's simple, just add it to your character class

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

but at first it will allow 5 spaces.

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

will be a little harder. It starts with two digits, and then with an optional group, starting with an extra place, followed by at least 1 digit. this group can be repeated 0 or more times.

It will fit

01 23 45 67 89

0123456789

01234 5679

+3

8 , , , :

^(?:\s*\d){8}$

, :

^(?:\s*-*\s*\d){8}$

+2

, , .

$input = '0123?> Abc -_#';
$output = preg_replace('#[^0-9- ]#', '', strtolower($input));
echo($output);

Do you want to simply confirm (match and abort) or clear, try to clear and continue?

+1
source

How about this?

preg_match("/^\d(\s*\d)*$/", $post['telephone'])
-2
source

All Articles