Advertisement
Guest User

Untitled

a guest
Aug 18th, 2019
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.94 KB | None | 0 0
  1. <?php
  2. function format_phone($phone = '', $convert = false, $trim = true)
  3. {
  4. // If we have not entered a phone number just return empty
  5. if (empty($phone)) {
  6. return '';
  7. }
  8.  
  9. // Strip out any extra characters that we do not need only keep letters and numbers
  10. $phone = preg_replace("/[^0-9A-Za-z]/", "", $phone);
  11.  
  12. // Do we want to convert phone numbers with letters to their number equivalent?
  13. // Samples are: 1-800-TERMINIX, 1-800-FLOWERS, 1-800-Petmeds
  14. if ($convert == true) {
  15. $replace = array('2'=>array('a','b','c'),
  16. '3'=>array('d','e','f'),
  17. '4'=>array('g','h','i'),
  18. '5'=>array('j','k','l'),
  19. '6'=>array('m','n','o'),
  20. '7'=>array('p','q','r','s'),
  21. '8'=>array('t','u','v'), '9'=>array('w','x','y','z'));
  22.  
  23. // Replace each letter with a number
  24. // Notice this is case insensitive with the str_ireplace instead of str_replace
  25. foreach($replace as $digit=>$letters) {
  26. $phone = str_ireplace($letters, $digit, $phone);
  27. }
  28. }
  29.  
  30. // If we have a number longer than 11 digits cut the string down to only 11
  31. // This is also only ran if we want to limit only to 11 characters
  32. if ($trim == true && strlen($phone)>11) {
  33. $phone = substr($phone, 0, 11);
  34. }
  35.  
  36. // Perform phone number formatting here
  37. if (strlen($phone) == 7) {
  38. return preg_replace("/([0-9a-zA-Z]{3})([0-9a-zA-Z]{4})/", "$1-$2", $phone);
  39. } elseif (strlen($phone) == 10) {
  40. return preg_replace("/([0-9a-zA-Z]{3})([0-9a-zA-Z]{3})([0-9a-zA-Z]{4})/", "($1) $2-$3", $phone);
  41. } elseif (strlen($phone) == 11) {
  42. return preg_replace("/([0-9a-zA-Z]{1})([0-9a-zA-Z]{3})([0-9a-zA-Z]{3})([0-9a-zA-Z]{4})/", "$1($2) $3-$4", $phone);
  43. }
  44.  
  45. // Return original phone if not 7, 10 or 11 digits long
  46. return $phone;
  47. }
  48. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement