简体   繁体   中英

Creating phone number format standard php

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.

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM