我在這裏有兩個問題。首先,我不知道如何使用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
我刪除了它們,它們之前有過引號,但仍然沒有這麼混亂 –