Php – Formatting phone number

formatting, php

For a decent and standardized php function I want to format a user inputted string to a std. international phone number format.
The string will be stripped from other characters as digits and +-signs. All spaces will be deleted.
After that I want to format the different strings to a standardized form:

+310612345678  -> +31 (0)61 234 567800310612345678  -> +31 (0)61 234 5678+31612345678   -> +31 (0)61 234 5678 //add a leading zero between brackets (0))0031612345678  -> +31 (0)61 234 567806 12345678   -> +31 (0)61 234 5678 //When no country code is given (no 00xx or +xx) than add the dutch one.

This is the function which i have allready:

function formatPhoneNumber($num){ //delete everything except digits and +  $number = preg_replace('/[^\d|\+]/', '', $number); if(substr($number,0,1) == '+' || substr($number, 0,2) == 00){  // }else{  $number = "+31".$number; } ///////// // formatting as mentioned above ///////// return $num}

I'm Looking for a algorithm to format the different ways of user inputted telephone numbers to one format: +31 (0)61 2345678

Best Solution

I'm not sure there's really an international standard for this beyond prefixing the country code. For examples of international phone number formatting, see here. Formatting will change depending on the country, and also on the type.

e.g. in the UK we have +44 (0)20 1234 1234 for landlines, and +44 (0)7700 123456 for mobiles.

Consequently, if you want to do this properly, I think you'll need to identify the country code, and then plug in a country-specific formatter.