如何使用PHPvalidation电话号码?

如何使用phpvalidation电话号码

由于电话号码必须符合模式,因此您可以使用正则expression式将input的电话号码与您在regexp中定义的模式相匹配。

PHP同时具有ereg和preg_match()函数。 我build议使用preg_match(),因为这种正则expression式有更多的文档。

一个例子

$phone = '000-0000-0000'; if(preg_match("/^[0-9]{3}-[0-9]{4}-[0-9]{4}$/", $phone)) { // $phone is valid } 

以下是我如何find有效的10位数的美国电话号码。 在这一点上,我假设用户想要我的内容,所以数字本身是可信的。 我在一个最终发送短信的应用程序中使用,所以我只是想要的原始数字不pipe。 格式化可以随时添加

 //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; 

编辑:如果有人感兴趣,我最终不得不把它移植到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)); 

我很大程度上取决于你打算支持哪些数字格式,以及你想要执行的数字分组的严格程度,使用空格和其他分隔符等。

看看这个类似的问题来获得一些想法。

然后是ITU-T的编号标准build议E.164