开发者

Creating phone number format standard php

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

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


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;
} 


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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜