Skip to content

Instantly share code, notes, and snippets.

@donnamcmaster
Last active March 3, 2020 00:00
Show Gist options
  • Save donnamcmaster/d9f0da6831bd70acd4057a2b4641877d to your computer and use it in GitHub Desktop.
Save donnamcmaster/d9f0da6831bd70acd4057a2b4641877d to your computer and use it in GitHub Desktop.
very basic phone number format for display
<?php
/**
* Phone Number Format
* - used to display phone numbers from a WooCommerce database
* - assumes local US numbers
* - very basic: removes non-digit characters, +1, adds dashes
* - props for base function to https://arjunphp.com/format-phone-number-using-php/
* - props for "+1" to https://simplysmartmedia.com/2013/11/php-phone-number-formatting-function/
*/
private static function phone_number_format ( $number ) {
// allow only digits, remove all other characters
$number = preg_replace("/[^\d]/","",$number);
// remove "1" if it's the first character
$number = preg_replace("/^1/", "", $number);
// check number length; add dashes iff it has 10 digits
$length = strlen($number);
if ( $length == 10 ) {
$number = preg_replace("/^1?(\d{3})(\d{3})(\d{4})$/", "$1-$2-$3", $number);
}
return $number;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment