php 如何使用PHP验证电话号码?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3090862/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to validate phone number using PHP?
提问by DEVOPS
How to validate phone number using php
如何使用php验证电话号码
采纳答案by Ben Rowe
Since phone numbers must conform to a pattern, you can use regular expressions to match the entered phone number against the pattern you define in regexp.
由于电话号码必须符合某种模式,因此您可以使用正则表达式将输入的电话号码与您在 regexp 中定义的模式进行匹配。
php has both ereg and preg_match() functions. I'd suggest using preg_match() as there's more documentation for this style of regex.
php 有 ereg 和 preg_match() 函数。我建议使用 preg_match() 因为有更多关于这种正则表达式的文档。
An example
一个例子
$phone = '000-0000-0000';
if(preg_match("/^[0-9]{3}-[0-9]{4}-[0-9]{4}$/", $phone)) {
// $phone is valid
}
回答by jmaculate
Here's how I find valid 10-digit US phone numbers. At this point I'm assuming the user wants my content so the numbers themselves are trusted. I'm using in an app that ultimately sends an SMS message so I just want the raw numbers no matter what. Formatting can always be added later
以下是我如何找到有效的 10 位美国电话号码。在这一点上,我假设用户想要我的内容,因此数字本身是可信的。我在一个最终发送 SMS 消息的应用程序中使用,所以无论如何我只想要原始数字。以后可以随时添加格式
//eliminate every char except 0-9
$justNums = preg_replace("/[^0-9]/", '', $string);
//eliminate leading 1 if its there
if (strlen($justNums) == 11) $justNums = preg_replace("/^1/", '',$justNums);
//if we have 10 digits left, it's probably valid.
if (strlen($justNums) == 10) $isPhoneNum = true;
Edit: I ended up having to port this to Java, if anyone's interested. It runs on every keystroke so I tried to keep it fairly light:
编辑:如果有人感兴趣,我最终不得不将其移植到 Java。它会在每次击键时运行,所以我尽量保持轻量级:
boolean isPhoneNum = false;
if (str.length() >= 10 && str.length() <= 14 ) {
//14: (###) ###-####
//eliminate every char except 0-9
str = str.replaceAll("[^0-9]", "");
//remove leading 1 if it's there
if (str.length() == 11) str = str.replaceAll("^1", "");
isPhoneNum = str.length() == 10;
}
Log.d("ISPHONENUM", String.valueOf(isPhoneNum));
回答by Ivar Bonsaksen
I depends heavily on which number formats you aim to support, and how strict you want to enforce number grouping, use of whitespace and other separators etc....
我在很大程度上取决于您打算支持哪种数字格式,以及您希望强制执行数字分组、使用空格和其他分隔符等的严格程度......
Take a look at this similar questionto get some ideas.
看看这个类似的问题以获得一些想法。
Then there is E.164which is a numbering standard recommendation from ITU-T

