3

Okay, so my code does work. But, I need to edit some of it. For example, I want it to allow numbers 7 or 10 numbers in length.
The second part is that it is not validating my numbers with - or () in them, which it should. I want it to be able to validate numbers with the parenthesis or hyphens, no letters.

<?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>";
}
?>
4

1 回答 1

0

You should look into a regular expression only solution. Something similar to:

//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}'
于 2012-05-15T02:28:36.357 回答