带国家/地区代码检查的电话号码的正则表达式 (RegEx)
我需要一个 PHP RegEx,通过它我可以使用以下标准验证电话号码格式:
- 不应包含除数字之外的任何内容;
- 不应以零开头,因为我需要添加国家/地区代码前缀;
- RegEx 中应包含允许的国家/地区代码列表;
- 国家代码后面的数字不能是零;
- 号码的最大长度不应超过 13 位数字。
在发布这个问题之前,我尝试在 Stack Overflow 上搜索,但找不到确切的解决方案。任何帮助将不胜感激。
编辑:我只希望用户以有效格式输入电话号码,因为目前我的客户在编写电话号码时会犯一些愚蠢的格式错误。我并不担心它实际上有效(可调用),因为用户会自己处理这个问题。
问候
I need a PHP RegEx through which I can validate a phone number format using the following criteria:
- Should not include anything except for numbers;
- Should not start with a zero as I need to have the country code prefixed;
- The list of allowed country codes should be there in RegEx;
- The digit immediately after the country code should not be a zero;
- The maximum length of the number should not exceed 13 digits.
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.
Edit: 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.
Regards
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不会为此烧伤我的手指。
仅通过查看电话号码,您无法判断它是否有效,即使它“看起来”有效,也可能不是您要查找的电话号码(即其他人的电话号码)。
你试图在错误的层面上解决问题。验证电话号码的唯一方法是实际调用它;)
满足您的条件的正则表达式:
国家/地区代码列表(用 | 分隔)后跟一个非 0 的数字,后跟任意次数的任意数字。
您无法在一个正则表达式中执行 13 长度检查和国家/地区检查,因为国家/地区代码的长度各不相同(至少据我所知)。
您可以通过通用正则表达式进行 13 长度检查,例如:
匹配长度最多为 13 个字符的任何内容
I wouldn't burn my fingers on this.
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:
list of country codes (seperated by | ) followed by a digit that is not 0, followed by any digit any number of times.
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:
Matching anything up to 13 characters long
对于意大利来说,这个系统将会失败。意大利电话号码的前导 0 是从国外拨打的。
其他一些国家可能也会发生这种情况,但意大利是最著名的。
对于较短的号码但添加了分机号,该规则将在多个国家/地区被打破。
3 位数的国家代码、3 位数的区号和 8 位数的用户号码,您就少了一个数字。
That system will fail for Italy. The leading 0 for Italian phone numbers is dialled from abroad.
They might be some other countries where that also happens, but Italy is the most well-known.
For shorter numbers but with an extension added, that rule will be broken in multiple countries.
With 3 digit country code, 3 digit area code and 8 digit subscriber number, you're a digit short.