Puddingboy
Puddingboy

Reputation: 127

Match phone numbers with lengths between 8-16 digits, ignoring ()+-

Consider the following:

+12 34 456 432
(12) 34 567 124
1234 56 78 90
(1234) 567 890
1234-567-890
1234 - 567 - 890
12 34 56 78
12-34-56-78

Assume these are all valid phone number structures

Can a regex be used to express: find at least 8 numbers,but not more than 16 and ignore spaces, round brackets, the plus symbol(once) and the minus.

My current working sample is a mess:

^([\+|\(]{1,2})?+(\d{2,4})+([ |-|\)]{1,2})?+(\d{2,3})+([ |-]{1})?+(\d{2,3})+([ |-]{1})?+(\d{2,3})?$

Even if phone number validation is recommended against. Is there not a simpler regex syntax for these things?

Upvotes: 1

Views: 473

Answers (4)

gnasher729
gnasher729

Reputation: 52602

Don't even think about it. Phone numbers are complicated. They are hugely complicated. Google has a decent library to handle phone numbers named libPhoneNumber.

And excuse me, but ignoring the "+" makes whatever you are doing totally, absolutely wrong. A plus is followed by the country code of some country, followed by a local phone number within that country (which needs to be parsed according to the rules of that country, and there are about 200). Without the "+", you have a phone number according to the local rules, and you need to find out which local rules apply. Which means your number can start with a code for dialing a foreign exchange instead of the "+", otherwise it is formatted according to local rules.

As a result, a number may be valid with the "+" and invalid without it or vice versa, and most likely refers to a different actual phone in totally different countries with or without the "+".

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627190

To just account for the number of digits and ingore the -, ), ( or spaces (allowing a + at the beginning), you can use the following regex:

^\+?(?:[ ()-]*\d){8,16}$

It matches

  • ^ - start of string
  • \+? - one or zero +
  • (?:[ ()-]*\d){8,16} - 8 to 16 sequences of...
    • [ ()-]* - 0 or more -, ), ( or a space characters
    • \d - a digit
  • $ - end of string

See the regex demo

Upvotes: 1

Thamilhan
Thamilhan

Reputation: 13313

Using preg_replace fetch numbers only, check for the valid length

<?php       
$ph = "(12) 34 567 124";
$len = strlen(preg_replace('/[^0-9]+/', '', $ph));
if($len >=8 && $len <=16)
    echo "Valid";
else 
    echo "Invalid";

Upvotes: 0

Thomas Ayoub
Thomas Ayoub

Reputation: 29451

This may ease your task.

First, remove everything that is not a number:

myString = myString.replace(/\D/g,'');

You'll get this:

1234456432
1234567124
1234567890
1234567890
1234567890
1234567890
12345678
12345678

Then just check for length:

if(myString.length >= 0 && myString.length <=16)
// Do stuff

Upvotes: 1

Related Questions