Phone numbers have got to be one of the most commonly gathered bits of information in forms. I created a little PHP function that formats them for the most common US strings, 7 or 10 digits.
The Function
// FORMAT PHONE NUMBERS function formatPhoneNumber($variableName) { global $$variableName; // Keep numbers only $$variableName = preg_replace("[^0-9]", "", $$variableName ); // Remove "1" if it's the first character $$variableName = preg_replace("/^1/", "", $$variableName); // format for 7 digit numbers if(strlen($$variableName) == 7) $$variableName = preg_replace("/([0-9]{3})([0-9]{4})/", "$1-$2", $$variableName); // format for 10 digit numbers if(strlen($$variableName) == 10) // 10 digit numbers $$variableName = preg_replace("/([0-9]{3})([0-9]{3})([0-9]{4})/", "($1) $2-$3", $$variableName); }
Calling the Function
if (isset($_POST['phoneNumber'])) { $phoneNumber = addslashes($_POST['phoneNumber']); formatPhoneNumber('phoneNumber'); } // Do something with the phone number, i.e. insert into a db...
Things This Doesn’t Account For:
Obviously, this does not perform any form validation. If anything other than a 7 or 10 digit number is submitted, it will only be stripped down to numbers.
1 reply on “PHP Phone Number Formatting Function”
[…] Update: I have updated this a bit and created a reusable function. You can find it here. […]