Created
February 21, 2017 15:27
-
-
Save NightOwlPrgmr/a8b7a813caf433a162435a030f9f3321 to your computer and use it in GitHub Desktop.
Validate and format phone numbers - retain country codes and extensions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function formatPhone($num) { | |
$num = preg_replace('/[^\dx]/i', '', $num); | |
preg_match('/(x)\.?:?\s*?(\d+)/i', $num, $ext); | |
if (!empty($ext)) { | |
$ext = ' ext ' . preg_replace('/\D/', '', $ext[0]); | |
$num = preg_replace('/(x)\.?:?\s*?(\d+)/i', '', $num); | |
} | |
$number = preg_replace('/\D/', '', $num); | |
$length = strlen($number); | |
if ($length == 7) { | |
$r = preg_replace("/(\d{3})(\d{4})/", "$1-$2", $number); | |
} else if ($length == 10) { | |
$r = preg_replace('/^1?(\d{3})(\d{3})(\d{4})$/', "$1-$2-$3", $number); | |
} else if ($length > 10 && $length < 13) { | |
$r = preg_replace('/^1?(\d{1,2})(\d{3})(\d{3})(\d{4})$/', "+$1 $2-$3-$4", $number); | |
} else if ($length == 13) { | |
$r = preg_replace('/^(\+\s*)?(\d{1,2})(\d{1})(\d{3})(\d{3})(\d{4})$/', "$1 $2-$3-$4-$5", $number); | |
} else { | |
$r = $number . ' - INVALID NUMBER'; | |
} | |
# apply the extension if available | |
if (!empty($ext)) { | |
$r = $r . $ext; | |
} | |
return $r; | |
} | |
$numbers = array( | |
'-234-567-8901', | |
'1-234-567-8901', | |
'1-234-567-8901 x1234', | |
'1-234-567-8901 ext1234', | |
'1 (234) 567-8901', | |
'1.234.567.8901', | |
'1/234/567/8901', | |
'12345678901', | |
'(+351) 282 43 50 50', | |
'90191919908', | |
'555-8909', | |
'001 6867684', | |
'001 6867684x1', | |
'1 (234) 567-8901', | |
'1-234-567-8901 x1234', | |
'1-234-567-8901 ext1234', | |
'1-234 567.89/01 ext.1234', | |
'1(234)5678901x1234', | |
'(123)8575973', | |
'(0055)(123)8575973', | |
'(123)456-7890', | |
'(123)-456-7890', | |
'(123) 456-7890', | |
'(123) 456-7890 x123', | |
'12 1234 123 1 x1111', | |
'12 12 12 12 12', | |
'12 1 1234 123456 x12345', | |
'+12 1234 1234', | |
'+12 12 12 1234', | |
'+12 1234 5678', | |
'+12 12345678', | |
'(123)456789', | |
'(123456789', | |
'(123 456 789', | |
'(123.456.789', | |
'(123-456-789', | |
'123)456789', | |
'123) 456 789', | |
'123).456.789', | |
'123)-456-789', | |
); | |
foreach ($numbers as $phone) { | |
echo $phone . ': ' . "\t\t" . formatPhone($phone) . PHP_EOL; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment