用于检查字符串是否包含数据库中的单词的函数

时间:2011-10-13 13:40:39

标签: php mysql

我有一个包含被阻止词汇列表的表格

+--------+------------------+
|  id    |  word            |
+--------+------------------+
|   1    |  this            |
|   2    |  word            |
|   3    |  is              |
|   4    |  blocked         |
+--------+------------------+

我需要做的是编写一个函数,检查字符串是否包含被阻止的单词(表中的单词),例如:

function blocked($string){
    if(***blocked***){
        return true;
    }else{
        return false;
    }
}

该函数应返回true,无论该单词是单独的单词,还是隐藏在另一个单词中:

$string = "I want to see if this string is blocked"; //returns `true` because it contains 'this', 'is' and 'blocked'


$string = "iwanttoseeifthisstringisblocked"; //returns `true`

希望我的问题很明确,

任何帮助表示赞赏

4 个答案:

答案 0 :(得分:5)

您可以使用此数据库或类似数据库查询:

select word from blocked_list where "you string" like concat("%", word, "%")

答案 1 :(得分:1)

将表格内容输入数组然后 - > <>

$comment = "iwanttoseeifthisstringisblocked";
$words = array('this','word','is','blocked');

function is_array_in_string($comment, $words)
{
    foreach ($words as $item)
    {
        if (strpos($comment, $item) !== false)
            return true;
    }
    return false;
}

答案 2 :(得分:0)

while ( $row = mysql_fetch_array($res) ){
   if ( !( strpos($your_string, $row['word']) === false ) ){
       return true;
   };
   return false;
}

其中$res是执行SELECT word FROM words

的结果

答案 3 :(得分:0)

如果您希望在PHP中完成,则需要使用strstr();功能。

但是您可以在MySQL查询中使用LIKE%来执行此操作