好的,所以我的代码确实有效。但是,我需要编辑一些。例如,我希望它允许长度为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 “$phone”</p><hr />";
// Check for 7 or 10 characters long
if (strlen($phone) < 7) {
++$failures;
echo "<p><small>Warning: “$phone” 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: “$phone” contains non numeric characters</small></p>";
}
if ($failures == 0)
echo "<p>“$phone” is valid</p>";
else
echo "<p>“$phone” is not valid</p>";
}
?>
答案 0 :(得分: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}'