Categories
Web Development

PHP Phone Number Formatting Function

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.

By Tim Bunch

Tim Bunch is a Web Developer from Rockaway Beach, Oregon. As a web standards fanatic, he passionately pursues best practices. He also actively engages people on a wide range of topics in a variety of social media networks. Tim is also an avid Wordpress developer, music maker, coffee drinker, and child raiser. @timbunch

1 reply on “PHP Phone Number Formatting Function”

Leave a Reply