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

(710)

Written by 

I am Sakthivel Madesh, a certified Salesforce Developer & Administrator working on Salesforce Technology since 2011. I am currently working in Techforce Services as Sr. Salesforce Developer. I have worked on multiple technologies Like PHP, Java, Salesforce, I am very passionate about Salesforce and to earn 13x Salesforce Certification. I love Trailhead for learning Salesforce Skill and Become a Trailhead Ranger too. I Love to Learn & Share my Salesforce knowledge to Salesforce Learners/Beginner using My Blog and Salesforce Community.

Leave a Reply