如果我的数据库my_table (id,word)
如下
我发布了一些文章
$name
和$comment
然后我想知道$name
和/或$comment
是否包含我存储在数据库中的单词my_table (id,word)
$name = "Manal Nor";
$comment = "Hello lovely world";
我现在只能将其应用于一个条目,例如$name
$name = "Manal Nor"; // As example no bad words
$sql = "SELECT * FROM my_table";
$result = mysql_query($sql);
$nameArray = explode(" ", $name);
$countname = count($nameArray);
$checkname = 0;
while ($row = mysql_fetch_assoc($result)) {
for ($i=0;$i<$countname;$i++) {
if (strcasecmp($nameArray[$i], $row['word']) == 0) {
$checkname = 1;
}
}
}
if ($checkname == 1) {
echo "banned";
exit;
}
else {
echo "passed";
}
但现在问题如何将其应用于$name
和/或$comment
,以便echo "banned";
$name
和/或$comment
包含my_table
答案 0 :(得分:2)
这里的技巧是用preg_split()
将单词字符上的两个变量分开,并使用结果数组为查询形成IN()
子句。
// Strip non-alpha, space characters
$name = preg_replace("/[^a-zA-Z ]/", "", $name);
$comment = preg_replace("/[^a-zA-Z ]/", "", $comment);
$namewords = explode(" ", $name);
$commentwords = explode(" ", $comment);
// Stick them together and escape
$allwords = array_merge($namewords, $commentwords);
// Surround each word in quotes
$allwords = array_unique($allwords);
$allwords = array_map(function($w) {return "'$w'";}, $allwords);
$allwords = implode(",", $allwords);
// Builds a query like
// SELECT * FROM my_table WHERE word IN ('all', 'words', 'from', 'comment', 'and', 'name');
$result = mysql_query("SELECT word FROM my_table WHERE word IN($allwords)");
if ($result) {
// If any rows were returned, the input contained a bad word.
if (mysql_num_rows($result) > 0) {
// Contains bad words. Ban user.
}
}
答案 1 :(得分:1)
从命令添加世界到。用
替换原始行$nameArray = array_merge(explode(" ", $name), explode(" ", $comment));