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.
1 reply on “Formatting Phone Numbers with PHP”
Thanks, Tim, regular expressions have always confused me and so it’s handy to have a library of useful snippets. I’ll be bookmarking this one.