Source: http://stackoverflow.com/questions/4708248/formatting-phone-numbers-in-php
This is a US phone formatter that works on more versions of numbers than any of the current answers.
$numbers = explode("\n", '(111) 222-3333
((111) 222-3333
1112223333
111 222-3333
111-222-3333
(111)2223333
+11234567890
1-8002353551
123-456-7890 -Hello!
+1 - 1234567890
');
foreach($numbers as $number)
{
print preg_replace('~.*(\d{3})[^\d]{0,7}(\d{3})[^\d]{0,7}(\d{4}).*~', '($1) $2-$3', $number). "\n";
}
And here is a breakdown of the regex:Cell: +1 999-(555 0001)
.* zero or more of anything "Cell: +1 "
(\d{3}) three digits "999"
[^\d]{0,7} zero or up to 7 of something not a digit "-("
(\d{3}) three digits "555"
[^\d]{0,7} zero or up to 7 of something not a digit " "
(\d{4}) four digits "0001"
.* zero or more of anything ")"
Updated: March 11, 2015 to use {0,7}
instead of {,7}
No comments:
Post a Comment