验证美国电话号码

3

好的,我的代码确实可以工作。但是,我需要对其进行编辑。例如,我希望它允许长度为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) 将字符串中的 ")" 子串替换为空字符串 ""。 - recursion.ninja
1个回答

0
你应该考虑使用正则表达式来解决问题。类似于以下代码:
//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
@Lobita 如果这是作业,请在以后的问题中添加[作业]标签。我已经为您添加了此标签。 - kba
@KristianAntonsen 好的,抱歉,我是新手。下次会注意的。 - Lobita
不太确定你的正则表达式是否已经转义。在PHP中,如果已经转义,则不需要这样做。否则,这两个正则表达式实际上是不匹配的。 - JM4

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接