【问题标题】:PHP contact form detect words in a text fieldPHP联系表单检测文本字段中的单词
【发布时间】:2013-11-25 07:13:44
【问题描述】:

我有一个带有文本字段的联系表,供人们输入其公司/组织的名称。如果表单包含以下任何单词或其变体,我想阻止提交:uc、uci、irvine、ucirvine。这是我的脚本:

// company group
    if(trim($_POST['cmpnyGrp']) === '') {
        $cmpnyGrpError = '<span class="error">Please enter your company or group name.</span>';
        $hasError = true;
    } else if (isset($_POST['cmpnyGrp'])) {
        $banned = array('uci', 'uc', 'ucirvine', 'uc-', 'uc ', 'irvine');
        $cmpnyGrpError = '<span class="error">If you are UCI, select UC under User Type and enter account string.</span>';
        $hasError = true;
    } else {
        $cmpnyGrp = trim($_POST['cmpnyGrp']);
    }

我知道我做错了什么,因为这不起作用。我不是程序员,但我正在尽我所能尝试了解该做什么。任何帮助将不胜感激。非常感谢。

【问题讨论】:

  • 你在哪里使用 $banned 数组?

标签: php forms words


【解决方案1】:

现在,您初始化$banned,然后从不使用它。你需要一个if(in_array($_POST['cmpnyGrp'], $banned) {...}。这将检查 cmpnyGrp 的值是否在禁用词数组中。但是请注意,这种形式的黑名单永远无法检查“uc”的每个可能变体。

【讨论】:

  • in_array, $_POST['cmpnyGrp'] 不包含任何完整的匹配字符串
  • 如何知道$_POST['cmpnyGrp']的内容? “或以下任何单词的变体”部分无法工作,因为它没有指定“变体”应该是什么。
【解决方案2】:

您声明了一系列被禁止的单词,但没有做任何事情。你需要像下面这样使用它:

foreach ($banned as $b) {
    if (strpos($_POST['cmpnyGrp'], $b) !== false) {
        $cmpnyGrpError = '<span class="error">If you are UCI, select UC under User Type and enter account string.</span>';
        $hasError = true;
        break;
    }
}

if (!isset($hasError)) {
    $cmpnyGrp = trim($_POST['cmpnyGrp']);
}

【讨论】:

  • 非常感谢,这很好用!!!这是另一个问题。有没有办法在禁用词中添加通配符?例如,如果 uc 是禁止词,则有人可能会输入 uc-irvine 或 uc-riverside。我可以输入uc之后的所有单词吗?我希望我说得通。谢谢!
【解决方案3】:

试试这个:

if(trim($_POST['cmpnyGrp']) === '') {
    $cmpnyGrpError = '<span class="error">Please enter your company or group name.</span>';
    $hasError = true;
} else {
    $banned = array('uci', 'uc', 'ucirvine', 'uc-', 'uc ', 'irvine');
    $found = false;
    foreach ($banned as $b) {
        if (stripos($_POST['cmpnyGrp'], $b)) {
            $found = true;
            break; // no need to continue looping, we found one match
        }
    }
    if ($found) {
        $cmpnyGrpError = '<span class="error">If you are UCI, select UC under User Type and enter account string.</span>';
        $hasError = true;
    } else {
        $cmpnyGrp = trim($_POST['cmpnyGrp']);
    }
}

【讨论】:

    猜你喜欢
    • 2016-08-11
    • 2014-03-11
    • 1970-01-01
    • 2020-07-15
    • 2016-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多