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