【问题标题】:function to check if a string contains a word from a database检查字符串是否包含数据库中的单词的函数
【发布时间】:2011-10-13 13:40:38
【问题描述】:

我有一个包含被屏蔽词列表的表格

+--------+------------------+
|  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`

希望我的问题很清楚,

任何帮助表示赞赏

【问题讨论】:

  • 从表格或 google Boyer-Moore 构造一个高效的正则表达式

标签: php mysql


【解决方案1】:

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

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

【讨论】:

【解决方案2】:

然后将表格的内容放入数组中->

$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;
}

【讨论】:

    【解决方案3】:
    while ( $row = mysql_fetch_array($res) ){
       if ( !( strpos($your_string, $row['word']) === false ) ){
           return true;
       };
       return false;
    }
    

    其中$res是执行SELECT word FROM words的结果

    【讨论】:

      【解决方案4】:

      如果你想在 PHP 中完成,你需要使用 strstr(); 函数。

      但是您可以在 MySQL 查询中使用 LIKE% 来做到这一点

      【讨论】:

        猜你喜欢
        • 2020-03-29
        • 2014-01-25
        • 2012-11-27
        • 2012-03-27
        • 1970-01-01
        • 2020-06-21
        • 1970-01-01
        • 2013-12-23
        • 1970-01-01
        相关资源
        最近更新 更多