Switch语句没有给出我想要的案例

时间:2017-08-30 19:52:26

标签: php regex mysqli

我这里有两个问题。首先,我不知道如何使用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;
}
?>

1 个答案:

答案 0 :(得分:0)

Try the following code, I commented as much as I could to try to show you what I did to (possibly) fix your issue.

mvn clean