tags:

views:

139

answers:

2

I found this resource when looking to commonly format user's phone numbers.... http://www.eyesis.ca/projects/formatphone.html

I was wondering if someone else might have a better solution.

A: 

They've been trying to get this into Zend_Framework for awhile, but it didn't make the cut for 1.10 for some reason.

Personally, unless there is a very good, well established library for validating input types (there does not appear to be one for PHP yet), I tend to just clean up the string as much as possible..

For phone numbers, I would simply trim whitespace, and come up with a fairly simple regex to try and keep things universal (replace "." with "-", etc).

Keep in mind though, that when something better comes along, you'll probably want to rewrite the logic inside that method to take advantage of it!

Stephen J. Fuhry
+2  A: 
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;
} 
Webnet