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

section31 on 07/08/08


Tagged


Versions (?)


Who likes this?

1 person has marked this snippet as a favorite

heinz1959


phone number format


Published in: PHP 


Formats a phone number as (xxx) xxx-xxxx or xxx-xxxx depending on the length.

  1. // Formats a phone number as (xxx) xxx-xxxx or xxx-xxxx depending on the length.
  2. function format_phone($phone)
  3. {
  4. $phone = preg_replace("/[^0-9]/", '', $phone);
  5.  
  6. if (strlen($phone) == 7)
  7. return preg_replace("/([0-9]{3})([0-9]{4})/", "$1-$2", $phone);
  8. elseif (strlen($phone) == 10)
  9. return preg_replace("/([0-9]{3})([0-9]{3})([0-9]{4})/", "($1) $2-$3", $phone);
  10. else
  11. return $phone;
  12. }

Report this snippet 

You need to login to post a comment.