带国家代码检查的电话号码的正则表达式(RegEx) [英] Regular Expression (RegEx) For Phone Numbers With Country Code Check

查看:477
本文介绍了带国家代码检查的电话号码的正则表达式(RegEx)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个PHP RegEx,通过它可以使用以下条件验证电话号码格式:

I need a PHP RegEx through which I can validate a phone number format using the following criteria:

  • 除了数字外,不应包含其他任何内容;
  • 不应以零开头,因为我需要在国家/地区代码前面加上前缀;
  • 允许的国家/地区代码列表应该在RegEx中;
  • 国家代码后的数字不应为零;
  • 该号码的最大长度不能超过13位数字.

我曾在发布此问题之前尝试搜索Stack Overflow,但找不到确切的解决方案.任何帮助将不胜感激.

I have tried to search on Stack Overflow before posting this question but couldn't find the exact solution. Any help would be highly appreciated.

我只希望用户以有效格式输入电话号码,因为目前我的客户在编写电话时会犯一些愚蠢的格式错误.我不担心它实际上是有效的(可呼叫的),因为用户会自己照顾自己.

I just want the user to enter the phone number in a valid format as currently my clients do some silly formatting mistakes while writing it. I am not worried about it being actually valid (call-able) as the user will take care of that himself.

致谢

推荐答案

我不会为此动手.

仅通过查看电话号码,您就无法判断该电话号码是否有效,即使它看起来"有效,也可能不是您要查找的电话号码(即其他人的电话号码).

Just by looking at a phone number you can not judge whether it is valid or not, and even if it 'looks' valid it might not be the phone number you're looking for (ie. someone else's phone number).

您正在尝试以错误的级别解决问题.验证电话号码的唯一方法是实际拨打电话;)

You're trying to solve the problem at the wrong level. The only way to validate a phone number is to actually CALL it ;)

满足您的条件的正则表达式:

A regex that suffices your criteria:

/^(1|20|21|..etc)[1-9][0-9]+$/

国家/地区代码列表(由|分隔),后跟一个非0的数字,再跟任意次数的任意数字.

list of country codes (seperated by | ) followed by a digit that is not 0, followed by any digit any number of times.

您不能在一个正则表达式中执行13长度检查和国家/地区检查,因为国家/地区代码的长度有所不同(至少据我所知). 您可以通过通用正则表达式执行13长度检查,例如:

You can can't do the 13-length check and the country check in one regex because the length of the country codes vary (to my knowledge at least). You can do the 13-length check by a generic regex like:

/^.{,13}$/

匹配长度不超过13个字符的任何内容

Matching anything up to 13 characters long

这篇关于带国家代码检查的电话号码的正则表达式(RegEx)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆