Formatting Phone Numbers in PHP

NightMICU picture NightMICU · Jan 16, 2011 · Viewed 191.7k times · Source

I am working on an SMS app and need to be able to convert the sender's phone number from +11234567890 to 123-456-7890 so it can be compared to records in a MySQL database.

The numbers are stored in the latter format for use elsewhere on the site and I would rather not change that format as it would require modifying a lot of code.

How would I go about this with PHP?

Thanks!

Answer

Xeoncross picture Xeoncross · May 24, 2012

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}