简体   繁体   English

创建电话号码格式标准php

[英]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 我在寻找常用格式的用户电话号码时发现了此资源。... 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. 他们已经尝试将放入Zend_Framework已有一段时间了,但是由于某种原因,它并没有达到1.10的标准。

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.. 就个人而言,除非有一个很好的,完善的用于验证输入类型的库(似乎还没有一个PHP库),否则我倾向于尽可能多地清理字符串。

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! 但是请记住,当出现更好的情况时,您可能希望重写该方法中的逻辑以利用它!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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