PHP phone number parser

2020-04-10 02:03发布

问题:

Building an application for UK & Ireland only but potentially it might extend to other countries. We have built an API and I'm trying to decided how A) to store phone numbers B) how to write a parser to understand all formats for entry and comparision.

e.g.

Say a user is in Ireland they add a phone number in these formats

0871231234

087 123 1234

087-1231234

+353871231234

Or any other combination of writing a number a valid way. We want to allow for this so a new number can be added to our database in a consistent way

So all the numbers above potentially would be stored as 00353871231234

The problem is I will need to do parsing for all uk as well. Are there any classes out there that can help with this process?

回答1:

Try http://www.braemoor.co.uk/software/telnumbers.shtml



回答2:

Use regular expressions. An info page can be found here. It should not be too hard to learn, and will be extremely useful to you.

Here is the regular expresssion for validating phone numbers in the United Kingdom:

^((\(?0\d{4}\)?\s?\d{3}\s?\d{3})|(\(?0\d{3}\)?\s?\d{3}\s?\d{4})|(\(?0\d{2}\)?\s?\d{4}\s?\d{4}))(\s?\#(\d{4}|\d{3}))?$

It allows 3, 4 or 5 digit regional prefix, with 8, 7 or 6 digit phone number respectively, plus optional 3 or 4 digit extension number prefixed with a # symbol. Also allows optional brackets surrounding the regional prefix and optional spaces between appropriate groups of numbers. More can be found here.

This Stackoverflow link should help you see how regular expressions can be used with phone numbers internationally.



回答3:

?php
$array = array
(
        '0871231234',
        '087 123 1234',
        '087-1231234',
        '+353871231234'
);

foreach($array as $a)
        if(preg_match("/(^[0-9]{10}$)|(^[0-9]{3}\ [0-9]{3}\ [0-9]{4}$)|(^[0-9]{3}\-[0-9]{7}$)|(^\+353[0-9]{9}$)/", $a))
        {
                // removes +35
                $a = preg_replace("/^\+[0-9]{2}/", '', $a);
                // removes first number
                $a = preg_replace("/^[0-9]{1}/", '', $a);
                // removes spaces and -
                $a = preg_replace("/(\s+)|(\-)/", '', $a);
                $a = "00353".$a;
                echo $a."\n";
        }
?>


回答4:

Design the basic functionality for the UK first add on to it later if needed. You can separate the logic for each country if needed at a later stage. I would tend on the side of cautious optimism, you want to be accepting as many numbers as possible?

  1. Strip out spaces, opening and closing brackets and -
  2. If number starts with a single 0 replace with 00
  3. If number starts with a + replace with a 00
  4. If it is numeric and has a total length of between 9 and 11 characters we are 'good'

As for storage you could store it as a string... or as an integer, with a second field that contains the Qty of prefix '0's

Use this for reference http://en.wikipedia.org/wiki/Telephone_numbers_in_the_United_Kingdom



标签: php class