Lee Price
Lee Price

Reputation: 5212

function to check if a string contains a word from a database

I have a table which contains a list of blocked words

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

What I need to do is write a function that checks if a string contains a blocked word (word in the table) for example:

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

The function should return true regardless if the word is a word on its own, or if its hidden in another word:

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


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

Hope my question is clear,

Any help appreciated

Upvotes: 2

Views: 2712

Answers (4)

Mob
Mob

Reputation: 11098

If you want it done in PHP you need to use the strstr(); function.

But you can do this using LIKE and % in your MySQL queries

Upvotes: 0

Tudor Constantin
Tudor Constantin

Reputation: 26861

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

where $res is the result of executing SELECT word FROM words

Upvotes: 0

Manse
Manse

Reputation: 38147

Get the contents of the table into an array then ->

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

Upvotes: 1

Alex
Alex

Reputation: 137

You can use this or similar database query:

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

Upvotes: 5

Related Questions