Format Phone Number


 / Published in: PHP
 

  1. function format_phone($phone)
  2. {
  3. $phone = preg_replace("/[^0-9]/", "", $phone);
  4.  
  5. if(strlen($phone) == 7)
  6. return preg_replace("/([0-9]{3})([0-9]{4})/", "$1-$2", $phone);
  7. elseif(strlen($phone) == 10)
  8. return preg_replace("/([0-9]{3})([0-9]{3})([0-9]{4})/", "($1) $2-$3", $phone);
  9. else
  10. return $phone;
  11. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: jgeewax on May 23, 2007

Should be noted that this is US based 7 or 10 digit dialing, and that it is NOT error-proof. If the function cannot figure out what to do with the number, it will have stripped all the non-numeric digits in the return value.

Posted By: DanielJay on September 13, 2007

Check out an "updated" version of this function: http://snipplr.com/view/3680/format-phone/

Posted By: kirkstrobeck on February 10, 2009

Thank you!

Posted By: BrianNY on January 21, 2010

For my need (local neighborhood and U.S. only) this is a great snippet. Thanks a whole lot !!

Posted By: mikevanwinkle on October 30, 2010

Yep, this worked great for me, thanks. And what's with all the spam.

Posted By: pell on January 27, 2012

Thank you very very much. :) This was great.

You need to login to post a comment.