Converts phone numbers to the formatting standard


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

Converts phone numbers to the formatting standard


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

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.