Posted By

pruntrut on 05/23/12


Tagged

php String


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

tux-world


Converts phone numbers to the formatting standard


 / Published in: PHP
 

URL: http://www.bluefrog.ca/2011/12/simple-phone-number-format-function/

Converts phone numbers to the formatting standard

  1. /**
  2. * Converts phone numbers to the formatting standard
  3. *
  4. * @param String $num A unformatted phone number
  5. * @return String Returns the formatted phone number
  6. */
  7. function formatPhone($num)
  8. {
  9. $num = preg_replace('/[^0-9]/', '', $num);
  10.  
  11. $len = strlen($num);
  12. if($len == 7)
  13. $num = preg_replace('/([0-9]{3})([0-9]{4})/', '$1-$2', $num);
  14. elseif($len == 10)
  15. $num = preg_replace('/([0-9]{3})([0-9]{3})([0-9]{4})/', '($1) $2-$3', $num);
  16.  
  17. return $num;
  18. }
  19.  
  20. // echo formatPhone('1 208 - 386 2934');
  21. // will print: (208) 386-2934 </code>

Report this snippet  

You need to login to post a comment.