Search code examples
phpregexdrupal-6phone-number

Identifying international phone numbers in string in PHP


I am trying to write a function that will pull valid phone numbers from a string that are valid somewhere on the planet. This is for a truly international site for an organization that has locations all over the globe and users in each location accessing it.

I mainly need this for a database migration. The previous sites that I am migrating from only used a simple text field with not instructions and no filtering. So this results in the phone fields being used in all sorts of creative ways.

What I am looking for it just to identify the first phone number in the string, then possibly remove any excessive characters before setting the result as user profile information.


Solution

  • you could use something like this:

    $pattern = '/([\+_\-\(\)a-z ]+)/';
    

    or

    $pattern = '/([^0-9]+)/i';
    
    $phone = preg_replace($pattern,'', $phone);
    

    or, use a php filter like:

    $phone = (int) filter_var($phone, FILTER_SANITIZE_NUMBER_INT);
    

    although with the filter you would need to be careful if you were allowing the value to start with "0".

    then, either way, check a range of lengths for allowed phone numbers ~6-12 or whatever your range covers.