我在这里有两个问题。首先,我不知道如何使用preg_match
来过滤数字和特殊字符,只允许包含字母和&。开关语句没有给出我想要的情况
此外,该脚本不能如何应用。我的意思是它的工作原理,但switch
语句只提供最后一个包含错误的字符串,如果我把它放在foreach
里面,它会给出第一个错误1次和第二个错误3次。
我在做什么错?请帮帮我!
<?php
// test variables
$act1 = "SUBSCRIBEa";
$act2 = "SUBSCRIBEb";
$act3 = "SUBSCRIBE";
$act4 = "SUBSCRIBE";
// set error false as default
$error = "false";
// check if variables are ready for use
if(!empty($act1) && !empty($act2) && !empty($act3) && !empty($act4)) {
$acts = [$act1, $act2, $act3, $act4];
// check the acts for lenght, numbers and special characters
// add all of the acts to an array to loop over
foreach($acts as $key => $value) {
if($key < 9) {
$errorKey = "0{$key}";
} else {
$errorKey = $key;
}
// check the lenght
if(strlen($value) > 15) {
$error = "true";
$errorNumber = $errorKey;
}
/* check for numbers and special characters
if(!preg_match('/[^a-z&A-Z]/', $value)){
$error = "true";
$errorNumber = $error_{$errorKey};
}
*/
// declare a whitelist of things that should not produce an error
$whiteList = [
'SUBSCRIBE',
'SUB & LIKE',
'LIKE & COMMENT',
'DISLIKE',
'COMMENT',
'LIKE',
'FOLLOW',
];
// check if value from act is in the whitelist declared above, if its not, set `$error` to true and set `$error_*` (with key) to "true" as well.
if(!in_array($value, $whiteList)) {
$error = "true";
$errorNumber = $errorKey;
}
}
}
// deliver the error message
switch($errorNumber){
case 00:
echo "Something went wrong here 1 :o";
break;
case 01:
echo "Something went wrong here 2 :o";
break;
case 02:
echo "Something went wrong here 3 :o";
break;
case 03:
echo "Something went wrong here 4 :o";
break;
}
?>
尝试引用'case'语句中的数字,它们是字符串。 – neuhaus
改为使用字符串:'case'02':'等 – BenM
我删除了它们,它们之前有过引号,但仍然没有这么混乱 –