我目前正在我正在处理的网站上实施评论部分。我想阻止人们留下愚蠢的评论。我有一张表格,其中包含我不想在评论中看到的单词。到目前为止,我使用array_intersect来比较它和表单。我首先使用explode将提交的表单从字符串更改为数组。如果未找到badWords,则将注释插入数据库。如果找到一个forbbiden词,那么现在我回应一些东西只是为了测试。我的问题是,即使找不到匹配,array_intersect似乎也会返回一些东西。在下面的代码中,print_r($ result)= Array()Array()。那是为什么?
<?php
if (isset($_POST['name']) && isset($_POST['commentaire'])) {
try {
$db = new PDO("mysql:host=$server;dbname=etvoila;charset=utf8", $username, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));}
catch (Exception $e)
{
die('Erreur : ' . $e->getMessage());
}
$name = htmlspecialchars($_POST['name']);
$comment = htmlspecialchars($_POST['commentaire']);
validateWords($name);
validateWords($comment);
if ($badWord = 1)
{
echo "Bad word found!";
} else {
$insert = $db->prepare("INSERT INTO comments (name, comment) VALUES (:name, :comment)");
$insert->execute(array(
'name' => $name,
'comment' => $comment
));
echo "Thank you";
}
}
function validateWords($sentence) {
$badWord = 0;
try {
$bdd = new PDO("mysql:host=$server;dbname=etvoila;charset=utf8", $username, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));}
catch (Exception $e)
{
die('Error : ' . $e->getMessage());
}
$sentence2 = trim($sentence, ".!?");
$sentence2 = strtolower($sentence2);
$sentence2 = explode(" ",$sentence2);
$select = $bdd->prepare('SELECT words FROM forbiddenWords');
$select->execute();
while ($forbiddenWords = $select->fetch()) {
$result = array_intersect($sentence2,$forbiddenWords);
if ($result) {
$badWord = 1;
}
}
}
?>
答案 0 :(得分:0)
这是array_intersect的默认行为,如果找不到匹配项,它将返回一个空数组。所以改变你的状况
if ($result) {
$badWord = 1;
}
到
if (is_array($result) && count($result) > 0) {
$badWord = 1;
}
因此,只有匹配才会发现您的$badWord
将为1