Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP regular expressions (phonenumber)

I'm having some trouble with a regular expression for phone numbers. I am trying to create a regex that is as broad as possible for european phone numbers. The phone number can start with a + or with two leading 0's, followed by a number in between 0 and 40. this is not necessary however, so this first part can also ignored. After that, it should all be numbers, grouped into pairs of at least two, with a whitespace or a - inbetween the groups.

The regex I have put together can be found below.

/((\+|00)+[0-4]+[0-9]+)?([ -]?[0-9]{2,15}){1,5}/

This should match the following structures

0031 34-56-78
0032123456789
0033 123 456 789
0034-123-456-789

+35 34-56-78
+36123456789
+37 123 456 789
+38-123-456-789
...

What it also matches according to my javascript

+32 a54b 67-0:

So I must have made a mistake somewhere, but I really can't see it. Any help would be appreciated.

like image 988
Michiel Standaert Avatar asked Oct 24 '11 12:10

Michiel Standaert


Video Answer


1 Answers

The problem is that you don't use anchors ^ $ to define the start and ending of the string and will therefore find a match anywhere in the string.

/^((\+|00)+[0-4]+[0-9]+)?([ -]?[0-9]{2,15}){1,5}$/

Adding anchors will do the trick. More about these meta characters can be found here.

like image 168
Marcus Avatar answered Sep 19 '22 06:09

Marcus