phone number format


/ Published in: PHP
Save to your folder(s)

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


Copy this code and paste it in your HTML
  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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.