Created
September 13, 2012 02:50
-
-
Save pulsedemon/3711532 to your computer and use it in GitHub Desktop.
Phone Number Formatting Method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Cleans up a phone number and outputs it in a consistent format | |
* @param string $number phone number to be formatted | |
* @return string formatted phone number | |
*/ | |
public function phone_number($number) { | |
// remove some characters | |
$stripped_number = preg_replace('/([\(\):\s\.-]+)/', '', $number); | |
// remove some possible chars from beginning | |
$stripped_number = strpbrk($stripped_number, '1234567890'); | |
// remove country code (1) if it exists | |
if(substr($stripped_number, 0, 1) == 1) { | |
// make sure to exclude any extra numbers that may be part of the string | |
if(strlen($stripped_number) >= 10) { | |
$stripped_number = substr($stripped_number, 1, 10); | |
} | |
else { | |
return $stripped_number; | |
} | |
} | |
// make sure phone number isn't longer than 10 digits | |
$stripped_number = substr($stripped_number, 0, 10); | |
// find phone number | |
preg_match('/([A-Za-z0-9-]+)/', $stripped_number, $matches); | |
// format the number | |
if(preg_match('/^(\d{3})(([A-Za-z\D]{7})|([A-Za-z0-9]{3})([A-Za-z0-9]{4}))$/', $matches[0], $final_matches)) { | |
$result = $final_matches[1]; | |
if($final_matches[3]) { | |
$result .= '-' .$final_matches[2]; | |
} | |
else { | |
$result .= '-' .$final_matches[4] . '-' . $final_matches[5]; | |
} | |
return $result; | |
} | |
else { | |
return $matches[0]; | |
} | |
} // public function phone_number |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment