【问题标题】:Validating USA phone numbers验证美国电话号码
【发布时间】:2012-05-22 12:48:51
【问题描述】:

好的,所以我的代码确实有效。但是,我需要编辑其中的一些。例如,我希望它允许长度为 7 或 10 个数字。
第二部分是它没有用-() 验证我的号码,这是应该的。我希望它能够验证带括号或连字符的数字,而不是字母。

<?php
$phoneNumbers = array("111-1111",
                      "(111) 111-1111",
                      "111-111-1111",
                      "111111",
                      "",
                      "aaa-aaaa");

foreach ($phoneNumbers as $phone) {
    $failures = 0;
    echo "<hr /><p>Checking &ldquo;$phone&rdquo;</p><hr />";

     // Check for 7 or 10 characters long
     if (strlen($phone) < 7) {
          ++$failures;
          echo "<p><small>Warning: &ldquo;$phone&rdquo; must be 7 or 10 characters</small></p>";
     }

     // Check for numbers
     if (!preg_match("/^([1]-)?[0-9]{3}-[0-9]{3}-[0-9]{4}$/i", $phone)) {
          ++$failures;
          echo "<p><small>Warning: &ldquo;$phone&rdquo; contains non numeric characters</small></p>";
     }

     if ($failures == 0) 
          echo "<p>&ldquo;$phone&rdquo; is valid</p>";
     else
          echo "<p>&ldquo;$phone&rdquo; is not valid</p>";
}
?>

【问题讨论】:

  • 使用str_replace 示例:$phoneNumber = str_replace(")","", $phoneNumber) 将“)”子字符串替换为“”空字符串;

标签: php validation phone-number


【解决方案1】:

您应该研究仅正则表达式的解决方案。类似于:

//Phone Number (North America)
//Matches 3334445555, 333.444.5555, 333-444-5555, 333 444 5555, (333) 444 5555 and all     combinations thereof.
//Replaces all those with (333) 444-5555
preg_replace('\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})', '(\1) \2-\3', $text);

//Phone Number (North America)
//Matches 3334445555, 333.444.5555, 333-444-5555, 333 444 5555, (333) 444 5555 and all combinations thereof.
'\(?[0-9]{3}\)?[-. ]?[0-9]{3}[-. ]?[0-9]{4}'

【讨论】:

  • 嗯,这是另一个任务。对于这个,我必须使用字符串操作函数。
  • @Lobita 如果是家庭作业,请在以后的问题中添加 [homework] 标签。这次我给你加了。
  • @KristianAntonsen 好的,抱歉,我是新手。下次会做。
  • 不完全确定,但您的正则表达式在这里逃脱了吗?这在 PHP if 中是不必要的。否则,两个正则表达式匹配实际上不匹配
猜你喜欢
  • 2010-09-15
  • 1970-01-01
  • 1970-01-01
  • 2011-09-21
  • 2011-08-16
  • 2011-03-22
  • 1970-01-01
  • 2011-05-22
  • 2010-11-11
相关资源
最近更新 更多