如何使用PHP验证电话号码?

时间:2010-06-22 06:48:35

标签: php regex

如何使用php验证电话号码

3 个答案:

答案 0 :(得分:27)

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

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

答案 1 :(得分:20)

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

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

一个例子

$phone = '000-0000-0000';

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

答案 2 :(得分:16)

我在很大程度上依赖于您希望支持的数字格式,以及您希望如何严格执行数字分组,使用空格和其他分隔符等等。

看看this similar question以获得一些想法。

然后有E.164这是来自ITU-T

的编号标准建议