我正在检查信用卡字段,以确保它们各有四位数字。
function creditcard ($creditCard1,$creditCard2,$creditCard3,$creditCard4)
{
$regexp="/^[0-9]{4}$/";
if (preg_match($regexp,$creditCard1,$creditCard2,$creditCard3,$creditCard4))//line 18
{
return TRUE;
}
else
{
echo'<script type="text/javascript">alert("Enter a valid credit card number.")</script>';
return FALSE;
}
}
$creditCard1=$_POST['creditCard1'];
$creditCard2=$_POST['creditCard2'];
$creditCard3=$_POST['creditCard3'];
$creditCard4=$_POST['creditCard4'];
$creditcard=creditcard($creditCard1,$creditCard2,$creditCard3,$creditCard4);
我收到此错误。
Warning: preg_match() expects parameter 4 to be long, string given in C:\xampp\htdocs\SFASC2\aa.php on line 18
我无法弄清楚我做错了什么,谢谢。有很多这样的问题,但没有一个给我解决方案..我一直在撞墙,毫无疑问忽视了明显的问题。
答案 0 :(得分:5)
preg_match一次只检查一个主题。
请尝试以下代码:
function creditcard($nums)
{
$regexp="/^[0-9]{4}$/";
for ($i = 0; $i < 4; $i++)
if (! preg_match($regexp, $nums[$i]))
return FALSE;
return TRUE;
}
$creditCard1 = $_POST['creditCard1'];
$creditCard2 = $_POST['creditCard2'];
$creditCard3 = $_POST['creditCard3'];
$creditCard4 = $_POST['creditCard4'];
$ok = creditcard([$creditCard1, $creditCard2, $creditCard3, $creditCard4]);
if (! $ok)
echo '<script type="text/javascript">alert("Enter a valid credit card number.")</script>';
答案 1 :(得分:4)
对于此用例,最好使用preg_grep而不是preg_match
,因为您对输入数组应用了单个正则表达式。使用preg_grep
的主要好处是可以避免循环输入。请考虑以下代码:
function creditcard($arr) {
static $re="/^\d{4}$/";
return (preg_grep($re, $arr) === $nums);
}
$result = creditcard(['5423', '1234', '1234', '1234']);
// returns true
$result = creditcard(['5423', 'A234', '1234', '1234']);
// returns false
PS:我将$re
声明为static
,因为该变量应声明为&amp;仅初始化一次。