Skip to Content

TheBlogReaders.com

Salesforce.com, PHP, MySQL, Javascript, Ajax, Htacces

US Phone Format Using PHP Function

Be First!
by June 17, 2014 PHP

US Phone Format Using PHP Function

Below PHP Example code will turn the poorly formatted US phone numbers entered by Customer and format with following formats:
(XXX)  XXX-XXX or XXX-XXX-XXXX

Example 1:

$phonenumber = “1234567890”;
echo “(“.substr($phonenumber, 0, 3).”) “.substr($phonenumber, 3, 3).”-“.substr($phonenumber,6);
Output: (123) 456-7890

Example 2:

$phonenumber= ‘+11234567890’;
if(preg_match( ‘/^\+\d(\d{3})(\d{3})(\d{4})$/’, $phonenumber,  $matches ) )
{
echo $result = $matches[1] . ‘-‘ .$matches[2] . ‘-‘ . $matches[3];
}
Output: 123-456-7890

Example 3:

$phonenumber= “1234567890”;
echo $formatted_number = preg_replace(“/^(\d{3})(\d{3})(\d{4})$/”, “$1-$2-$3”, $phonenumber);
Output: 123-456-7890

(709)

Previous
Next

Leave a Reply