Skip to content

Instantly share code, notes, and snippets.

@prajwal-stha
Created August 1, 2017 15:54
Show Gist options
  • Select an option

  • Save prajwal-stha/bf2140a332d110a2d7d3347d3b378784 to your computer and use it in GitHub Desktop.

Select an option

Save prajwal-stha/bf2140a332d110a2d7d3347d3b378784 to your computer and use it in GitHub Desktop.
Format phone number in US format
function format_phone_us($phone) {
// note: making sure we have something
if(!isset($phone{3})) { return ''; }
// note: strip out everything but numbers
$phone = preg_replace("/[^0-9]/", "", $phone);
$length = strlen($phone);
switch($length) {
case 7:
return preg_replace("/([0-9]{3})([0-9]{4})/", "$1-$2", $phone);
break;
case 10:
return preg_replace("/([0-9]{3})([0-9]{3})([0-9]{4})/", "($1) $2-$3", $phone);
break;
case 11:
return preg_replace("/([0-9]{1})([0-9]{3})([0-9]{3})([0-9]{4})/", "$1($2) $3-$4", $phone);
break;
default:
return $phone;
break;
}
}
// usage
$phone = '2142234736';
$phone = format_phone_us( $phone);
echo $phone;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment