Checking US Phone Numbers

Ok, so my code really works. But I need to edit some of them. For example, I want it to contain numbers 7 or 10 numbers.
The second part is that it does not confirm my numbers with -or ()in them, which is what should be. I want him to be able to check numbers with brackets or hyphens, without 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>";
}
?>
+3
source share
1 answer

You should look for a solution for regular expressions only. Something like:

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

All Articles