Categories
Web Development

Formatting Phone Numbers with PHP

When adding a phone number field to a form, it’s nice to format it (if it isn’t already). This doesn’t replace anything you would do to validate your form via Javascript. But it does create that little extra bit of uniformity, even if it is slightly redundant.

When adding a phone number field to a form, it’s nice to format it (if it isn’t already). This doesn’t replace anything you would do to validate your form via Javascript. But it does create that little extra bit of uniformity, even if it is slightly redundant.

Update: I have updated this a bit and created a reusable function. You can find it here

The HTML Input Element

<input type="text" value="" name="inputPhone" />

Format the Phone Number with PHP

$inputPhone = $_POST['inputPhone'];
// Start By Scrubbing Everything Except Numbers
$inputPhone = preg_replace("/[^0-9]/", "", $inputPhone);
// If it is a 7 digit number
if(strlen($inputPhone) == 7)
$inputPhone = preg_replace("/([0-9]{3})([0-9]{4})/", "$1-$2", $inputPhone);
// If it is a 10 digit number
if(strlen($inputPhone) == 10)
$inputPhone = preg_replace("/([0-9]{3})([0-9]{3})([0-9]{4})/", "($1) $2-$3", $inputPhone);

As you can see, there really isn’t any limit here as far as formatting goes. You could even set up an action if the number is not 7 or 10 digits long.

if(strlen($inputPhone) != 7 or strlen($inputPhone) != 10) {
// reject the number, or return an error message
}

Again, you should still check things via jQuery/Javascript first to ensure good input. This serves as a good backup and helps ensure properly formatted phone numbers are in your database.

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 “Formatting Phone Numbers with PHP”

Leave a Reply