Voici ma solution réservée aux États-Unis, avec l'indicatif régional en tant que composant facultatif, le délimiteur requis pour l'extension et les commentaires regex:
function formatPhoneNumber($s) {
$rx = "/
(1)?\D* # optional country code
(\d{3})?\D* # optional area code
(\d{3})\D* # first three
(\d{4}) # last four
(?:\D+|$) # extension delimiter or EOL
(\d*) # optional extension
/x";
preg_match($rx, $s, $matches);
if(!isset($matches[0])) return false;
$country = $matches[1];
$area = $matches[2];
$three = $matches[3];
$four = $matches[4];
$ext = $matches[5];
$out = "$three-$four";
if(!empty($area)) $out = "$area-$out";
if(!empty($country)) $out = "+$country-$out";
if(!empty($ext)) $out .= "x$ext";
// check that no digits were truncated
// if (preg_replace('/\D/', '', $s) != preg_replace('/\D/', '', $out)) return false;
return $out;
}
Et voici le script pour le tester:
$numbers = [
'3334444',
'2223334444',
'12223334444',
'12223334444x5555',
'333-4444',
'(222)333-4444',
'+1 222-333-4444',
'1-222-333-4444ext555',
'cell: (222) 333-4444',
'(222) 333-4444 (cell)',
];
foreach($numbers as $number) {
print(formatPhoneNumber($number)."<br>\r\n");
}