Home PHP US Phone Format Using PHP Function

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

You may also like

Leave a Comment