验证美国电话号码


Validating USA phone numbers

好的,所以我的代码确实有效。 但是,我需要编辑其中的一些。 例如,我希望它允许数字 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>";
}
?>

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

//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}'