/ Published in: PHP
URL: http://www.wlscripting.com/tutorial/49
This script formats USA based phone numbers and has the option to convert phone numbers with letters into numbers.
Expand |
Embed | Plain Text
function formatPhone($phone = '', $convert = false, $trim = true) { // If we have not entered a phone number just return empty return ''; } // Strip out any extra characters that we do not need only keep letters and numbers // Do we want to convert phone numbers with letters to their number equivalent? // Samples are: 1-800-TERMINIX, 1-800-FLOWERS, 1-800-Petmeds if ($convert == true) { '3'=>array('d','e','f'), '4'=>array('g','h','i'), '5'=>array('j','k','l'), '6'=>array('m','n','o'), '7'=>array('p','q','r','s'), '8'=>array('t','u','v'), '9'=>array('w','x','y','z')); // Replace each letter with a number // Notice this is case insensitive with the str_ireplace instead of str_replace foreach($replace as $digit=>$letters) { $phone = str_ireplace($letters, $digit, $phone); } } // If we have a number longer than 11 digits cut the string down to only 11 // This is also only ran if we want to limit only to 11 characters } // Perform phone number formatting here 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); } // Return original phone if not 7, 10 or 11 digits long return $phone; }
Comments
Subscribe to comments
You need to login to post a comment.

Added support for mobile or cell phone detection (Australia)
And:
Great script, I have an addition for php 4 users:
Opps, sorry that comment didn't get all my updates:
From line 8, add check for php 4, and replace with lowercase string // Strip out any extra characters that we do not need only keep letters and numbers $phone = preg_replace("/[^0-9A-Za-z]/", "", $phone);
// check for php version 4 if(substr(phpversion(), 0, 1) == '4') $phone = strtolower($phone);
Line 24, again check for php 4 and use strreplace instead of strireplace foreach($replace as $digit=>$letters) { if(substr(phpversion(), 0, 1) == '5') $phone = strireplace($letters, $digit, $phone); else $phone = strreplace($letters, $digit, $phone); }