November 17th, 2006

Parse and format phone numbers with PHP

This is a function that uses the inbuilt PHP sscanf funtion to format phone numbers that users input into a form into a perfect number. The functino strips all non-numeric characters (dashes, dots, parantheses), extracts extensions, and even picks up the area and country code.


function formatPhone($phone) {
       if (empty($phone)) return "";
       if (strlen($phone) == 7)
               sscanf($phone, "%3s%4s", $prefix, $exchange);
       else if (strlen($phone) == 10)
               sscanf($phone, "%3s%3s%4s", $area, $prefix, $exchange);
       else if (strlen($phone) > 10)
               if(substr($phone,0,1)=='1') {
                                 sscanf($phone, "%1s%3s%3s%4s", $country, $area, $prefix, $exchange);
                             }
                             else{
                                 sscanf($phone, "%3s%3s%4s%s", $area, $prefix, $exchange, $extension);
                               }
       else
               return "unknown phone format: $phone";
       $out = "";
       $out .= isset($country) ? $country.' ' : '';
       $out .= isset($area) ? '(' . $area . ') ' : '';
       $out .= $prefix . '-' . $exchange;
       $out .= isset($extension) ? ' x' . $extension : '';
       return $out;
}
Share

2 Responses to ' Parse and format phone numbers with PHP '

Subscribe to comments with RSS or TrackBack to ' Parse and format phone numbers with PHP '.

  1. efoiv said,

    on March 2nd, 2008 at 1:46 am

    i was looking for something exactly like this however something appears to not be working correctly with the code. I've tried working with it and can't for the life of me figure out where to begin.

    any chance you might be able to revise this?

    I started working out my own idea and got half way and decided there are too many possible entries that could be submitted. You idea seems to cover common formats and then fall back to unknown and let it slide by.

    looks like we are both heading down the same idea though

    thanks for the inspiration :)

  2. dmitry said,

    on August 6th, 2008 at 10:39 am

    this code is broken in more ways than one. not sure why it was posted. take the two consecutive else statements, for example. wtF?

Leave a reply

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word