Posted By


naz on 03/03/09

Tagged


Statistics


Viewed 1061 times
Favorited by 9 user(s)

Phone number beutifier


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

This function clean up phone number and present it in styled way.


Copy this code and paste it in your HTML
  1. function format_phone($phone)
  2. {
  3. $prefix = null;
  4.  
  5. //Check if number has international prefix
  6. switch(true){
  7. case substr($phone, 0, 1) == '+':
  8. $phone = substr($phone, 1);
  9. $prefix = '+';
  10. break;
  11. case substr($phone, 0, 2) == '00':
  12. $phone = substr($phone, 2);
  13. $prefix = '+';
  14. break;
  15. }
  16.  
  17. //Strip all non numeric characters
  18. $phone = preg_replace("/[^0-9]/", '', $phone);
  19.  
  20. switch(strlen($phone)){
  21. case 6:
  22. return preg_replace("/([0-9]{2})([0-9]{2})([0-9]{2})/", "$1-$2-$3", $phone);
  23. break;
  24. case 7:
  25. return preg_replace("/([0-9]{3})([0-9]{4})/", "$1-$2", $phone);
  26. break;
  27. case 10:
  28. return preg_replace("/([0-9]{3})([0-9]{3})([0-9]{4})/", "($1) $2-$3", $phone);
  29. break;
  30. case 11:
  31. return preg_replace("/([0-9]{3})([0-9]{4})([0-9]{4})/", $prefix . " ($1) $2-$3", $phone);
  32. break;
  33. case 12:
  34. return preg_replace("/([0-9]{4})([0-9]{4})([0-9]{4})/", $prefix . " ($1) $2-$3", $phone);
  35. break;
  36. default:
  37. return $phone;
  38. break;
  39. }
  40. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.