Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if string contains word in array [duplicate]

This is for a chat page. I have a $string = "This dude is a mothertrucker". I have an array of badwords: $bads = array('truck', 'shot', etc). How could I check to see if $string contains any of the words in $bad?
So far I have:

        foreach ($bads as $bad) {
        if (strpos($string,$bad) !== false) {
            //say NO!
        }
        else {
            // YES!            }
        }

Except when I do this, when a user types in a word in the $bads list, the output is NO! followed by YES! so for some reason the code is running it twice through.

like image 223
user1879926 Avatar asked Sep 07 '25 12:09

user1879926


2 Answers

function contains($str, array $arr)
{
    foreach($arr as $a) {
        if (stripos($str,$a) !== false) return true;
    }
    return false;
}
like image 190
Nirav Ranpara Avatar answered Sep 09 '25 02:09

Nirav Ranpara


1) The simplest way:

if ( in_array( 'three',  ['one', 'three', 'seven'] ))
...

2) Another way (while checking arrays towards another arrays):

$keywords=array('one','two','three');
$targets=array('eleven','six','two');
foreach ( $targets as $string ) 
{
  foreach ( $keywords as $keyword ) 
  {
    if ( strpos( $string, $keyword ) !== FALSE )
     { echo "The word appeared !!" }
  }
}
like image 40
T.Todua Avatar answered Sep 09 '25 00:09

T.Todua