简体   繁体   English

PHP:电话号码解析

[英]PHP: Telephone number parsing

I'm looking for some way to validate telephone numbers in PHP, which may be entered in any of the various formats that exist. 我正在寻找一些方法来验证PHP中的电话号码,可以用现有的各种格式输入。 If it helps, I'm able to restrict the problem's domain to just US phone numbers (or international numbers - one or the other, but not both). 如果它有帮助,我可以将问题的域限制为仅美国电话号码(或国际号码 - 一个或另一个,但不是两个)。

I've tried looking for custom filters for filter_var() , an equivalent to strtotime() for phone numbers, or just plain vanilla parsing libraries, but haven't had much luck. 我曾尝试为filter_var()寻找自定义过滤器,相当于strtotime()用于电话号码,或者只是简单的vanilla解析库,但没有太多运气。

If needed, I can design a custom solution, but I prefer not to if one already exists, because A) mine will surely not be as robust, and B) I don't like reinventing the wheel. 如果需要,我可以设计一个自定义解决方案,但我不愿意,如果一个已经存在,因为A)我的肯定不会那么健壮,而B)我不喜欢重新发明轮子。

Use regex, the following will Match things like 3334445555, 333.444.5555, 333-444-5555, 333 444 5555, (333) 444 5555 and all combinations thereof. 使用正则表达式,以下将匹配诸如3334445555,333.444.5555,333-444-5555,333 444 5555,(333)444 5555及其所有组合之类的东西。 and then replaces all those with (333) 444-5555 然后用(333)444-5555替换所有那些

preg_replace('\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})', '(\1) \2-\3', $text);

'Parsing' phone numbers is not a native PHP thing to do. '解析'电话号码不是本机PHP的事情。

You need to specify yourself what 'valid' phonenumbers are - this should be done by validating the input up against a specified format or perhaps a regular expression. 您需要自己指定“有效”的电话号码 - 这应该通过根据指定格式或正则表达式验证输入来完成。

There is no way PHP can know what 'a valid phonenumber' is. PHP无法知道'有效的phonenumber'是什么。

I'm not aware of all US phone number formats, but i'm guessing this is a general idea that you can extend: 我不知道所有美国电话号码格式,但我猜这是一个可以扩展的一般想法:

function validate_phone($phone) {
  // replace everything except numbers
  $phone = preg_replace('~[^\dx]~', '', $phone);

  return preg_match('~^\d{11}(x\d{4})?$~', $phone);
}


// $phone = 12345678901;
$phone = '1-234-567-8901x1234';
$valid = filter_var($phone, FILTER_CALLBACK, array(
  'options' => 'validate_phone'
));

if ($valid) {
  echo "It's valid!";
};

This code supports or eleven digit numbers(with dashes, spaces, dots inside) and extended format with x2134 suffix. 此代码支持或十一位数字(内部带有破折号,空格,点)和带有x2134后缀的扩展格式。

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

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