We Recommend

Wicked Cool PHP: Real-World Scripts That Solve Difficult Problems Wicked Cool PHP: Real-World Scripts That Solve Difficult Problems
Wicked Cool PHP contains a wide variety of scripts to process credit cards, check the validity of email addresses, template HTML, and serve dynamic images and text.


Posted By

tylerhall on 12/31/69


Tagged

regex phone number format


Versions (?)


Who likes this?

22 people have marked this snippet as a favorite

xhtmled
luxuryluke
mate
jkochis
shamrog12
irdial
blakeb
dmarten
demods
hudge
benrasmusen
marteki
bioascii
SpinZ
dyesin
nerdfiles
coylOne
blackabee
section31
jamesming
mrjthethird
elgermano


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/

You need to login to post a comment.