Create phone number format in php standard format
I found this resource on the usual formatting of user phone numbers .... http://www.eyesis.ca/projects/formatphone.html
I was wondering if someone else might have a better solution.
+2
a source to share
2 answers
function formatPhone($string)
{
$number = trim(preg_replace('#[^0-9]#s', '', $string));
$length = strlen($number);
if($length == 7) {
$regex = '/([0-9]{1})([0-9]{3})([0-9]{3})([0-9]{4})/';
$replace = '$1-$2';
} elseif($length == 10) {
$regex = '/([0-9]{3})([0-9]{3})([0-9]{4})/';
$replace = '($1) $2-$3';
} elseif($length == 11) {
$regex = '/([0-9]{1})([0-9]{3})([0-9]{3})([0-9]{4})/';
$replace = '$1 ($2) $3-$4';
}
$formatted = preg_replace($regex, $replace, $number);
return $formatted;
}
+4
a source to share
They tried to get this one in Zend_Framework for a while, but for some reason it didn't do the 1.10 cut.
Personally, unless you have a very good, well-installed library for checking input types (PHP doesn't exist yet), I try to clean up the line as much as possible.
For phone numbers, I would just trim the spaces and come up with a pretty simple regex to try and keep things universal (replace "." With "-", etc.).
Keep in mind that when something better comes along, you probably want to rewrite the logic inside this method to take advantage of it!
0
a source to share