Skip to content

Instantly share code, notes, and snippets.

@jonbrockett
Created January 17, 2019 14:31
Show Gist options
  • Select an option

  • Save jonbrockett/d80e0a10a34091dc60d982db8e02626e to your computer and use it in GitHub Desktop.

Select an option

Save jonbrockett/d80e0a10a34091dc60d982db8e02626e to your computer and use it in GitHub Desktop.
Format Phone Number (Custom Function)
<?php
/**
* Format Phone Number
*
* This function takes a 10 digit phone number and formats it
*/
function format_phone($s) {
$rx = "/
(1)?\D* # optional country code
(\d{3})?\D* # optional area code
(\d{3})\D* # first three
(\d{4}) # last four
(?:\D+|$) # extension delimiter or EOL
(\d*) # optional extension
/x";
preg_match($rx, $s, $matches);
if(!isset($matches[0])) return false;
$country = $matches[1];
$area = $matches[2];
$three = $matches[3];
$four = $matches[4];
$ext = $matches[5];
$out = "$three-$four";
if(!empty($area)) $out = "$area-$out";
if(!empty($country)) $out = "+$country-$out";
if(!empty($ext)) $out .= "x$ext";
// check that no digits were truncated
// if (preg_replace('/\D/', '', $s) != preg_replace('/\D/', '', $out)) return false;
return $out;
}
/** Add function to format phone numbers */
require_once( 'library/format-phone.php' );
<?php echo format_phone($phone_number); ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment