【发布时间】:2012-05-22 12:48:51
【问题描述】:
好的,所以我的代码确实有效。但是,我需要编辑其中的一些。例如,我希望它允许长度为 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>";
}
?>
【问题讨论】:
-
使用str_replace 示例:
$phoneNumber = str_replace(")","", $phoneNumber)将“)”子字符串替换为“”空字符串;
标签: php validation phone-number