Formatting Phone Numbers In PHP

To format a phone number before displaying it on the page, you can use the following function. This function insert spaces so that the phone number becomes easier to read by the user. You can modify the function to replace the spaces with hyphen or parenthesis if you want.


//FUNCTION TO FORMAT PHONE NUMBERS
function formatPhone($num)
{
$num = preg_replace('/[^0-9]/', '', $num);
$len = strlen($num);

if($len<=6)
{
$num = preg_replace('/([0-9]{3})([0-9]{3})/', ' $1 $2', $num);
}
else if(($len>6)&&($len<=9))
{
$num = preg_replace('/([0-9]{3})([0-9]{3})([0-9]{1})/', ' $1 $2 $3', $num);
}
else if($len == 10)
{
$num = preg_replace('/([0-9]{3})([0-9]{3})([0-9]{4})/', ' $1 $2 $3', $num);
}
else if($len>10)
{
$num = preg_replace('/([0-9]{3})([0-9]{3})([0-9]{4})([0-9]{1})/', ' $1 $2 $3 $4', $num);
}
return $num;
}
//END OF FUNCTION TO FORMAT PHONE NUMBERS

Advertisements

One thought on “Formatting Phone Numbers In PHP

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s