Posted By

naz on 03/03/09


Tagged

regex php phone String parser


Versions (?)

Who likes this?

16 people have marked this snippet as a favorite

Bluewall
jamesming
naz
rezzz
pezland
f3ze
nb109
Premier13
jachin
jealousy
huynguye
sultano
tapdrup
bobbym245
mecha
tux-world


Phone number beutifier


 / Published in: PHP
 

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

  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
Posted By: MMDeveloper on March 4, 2009

nice

You need to login to post a comment.