Php check if string contains words in array

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.

Moozy

4,4173 gold badges17 silver badges18 bronze badges

asked Dec 10, 2012 at 6:00

3

function contains($str, array $arr)
{
    foreach($arr as $a) {
        if (stripos($str,$a) !== false) return true;
    }
    return false;
}

Robert Went

2,8442 gold badges17 silver badges18 bronze badges

answered Dec 10, 2012 at 6:06

Php check if string contains words in array

Nirav RanparaNirav Ranpara

15.8k4 gold badges43 silver badges57 bronze badges

5

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 !!" }
  }
}

answered May 30, 2013 at 12:46

Php check if string contains words in array

T.ToduaT.Todua

50.1k19 gold badges216 silver badges213 bronze badges

1

can you please try this instead of your code

$string = "This dude is a mothertrucker";
$bads = array('truck', 'shot');
foreach($bads as $bad) {
    $place = strpos($string, $bad);
    if (!empty($place)) {
        echo 'Bad word';
        exit;
    } else {
        echo "Good";
    }
}

HeavenCore

7,3856 gold badges46 silver badges59 bronze badges

answered Dec 10, 2012 at 7:11

Php check if string contains words in array

SanjaySanjay

76114 silver badges25 bronze badges

1

You can flip your bad word array and do the same checking much faster. Define each bad word as a key of the array. For example,

//define global variable that is available to too part of php script
//you don't want to redefine the array each time you call the function
//as a work around you may write a class if you don't want global variable
$GLOBALS['bad_words']= array('truck' => true, 'shot' => true);

function containsBadWord($str){
    //get rid of extra white spaces at the end and beginning of the string
    $str= trim($str);
    //replace multiple white spaces next to each other with single space.
    //So we don't have problem when we use explode on the string(we dont want empty elements in the array)
    $str= preg_replace('/\s+/', ' ', $str);

    $word_list= explode(" ", $str);
    foreach($word_list as $word){
        if( isset($GLOBALS['bad_words'][$word]) ){
            return true;
        }
    }
    return false;
}

$string = "This dude is a mothertrucker";

if ( !containsBadWord($string) ){
    //doesn't contain bad word
}
else{
    //contains bad word
}

In this code we are just checking if an index exist rather than comparing bad word with all the words in the bad word list.
isset is much faster than in_array and marginally faster than array_key_exists.
Make sure none of the values in bad word array are set to null.
isset will return false if the array index is set to null.

answered Dec 3, 2013 at 16:57

1

Put and exit or die once it find any bad words, like this

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

answered Dec 10, 2012 at 6:07

Php check if string contains words in array

SanjaySanjay

76114 silver badges25 bronze badges

6

There is a very short php script that you can use to identify bad words in a string which uses str_ireplace as follows:

$string = "This dude is a mean mothertrucker";
$badwords = array('truck', 'shot', 'ass');
$banstring = ($string != str_ireplace($badwords,"XX",$string))? true: false;
if ($banstring) {
   echo 'Bad words found';
} else {
    echo 'No bad words in the string';
}

The single line:

$banstring = ($string != str_ireplace($badwords,"XX",$string))? true: false;

does all the work.

answered Jul 21, 2017 at 11:29

Php check if string contains words in array

ClintonClinton

9731 gold badge11 silver badges19 bronze badges

2

You can do the filter this way also

$string = "This dude is a mothertrucker";
if (preg_match_all('#\b(truck|shot|etc)\b#', $string )) //add all bad words here.       
    {
  echo "There is a bad word in the string";
    } 
else {
    echo "There is no bad word in the string";
   }

answered Jun 27, 2019 at 12:56

Php check if string contains words in array

1

Wanted this?

$string = "This dude is a mothertrucker"; 
$bads = array('truck', 'shot', 'mothertrucker');

    foreach ($bads as $bad) {
        if (strstr($string,$bad) !== false) {
            echo 'NO
'; } else { echo 'YES
'; } }

answered Dec 10, 2012 at 6:11

LeninLenin

57016 silver badges36 bronze badges

2

If you want to do with array_intersect(), then use below code :

function checkString(array $arr, $str) {

  $str = preg_replace( array('/[^ \w]+/', '/\s+/'), ' ', strtolower($str) ); // Remove Special Characters and extra spaces -or- convert to LowerCase

  $matchedString = array_intersect( explode(' ', $str), $arr);

  if ( count($matchedString) > 0 ) {
    return true;
  }
  return false;
}

answered Aug 17, 2017 at 6:28

Php check if string contains words in array

Irshad KhanIrshad Khan

5,3402 gold badges42 silver badges38 bronze badges

0

I would go that way if chat string is not that long.

$badwords = array('mothertrucker', 'ash', 'whole');
$chatstr = 'This dude is a mothertrucker';
$chatstrArr = explode(' ',$chatstr);
$badwordfound = false;
foreach ($chatstrArr as $k => $v) {
    if (in_array($v,$badwords)) {$badwordfound = true; break;}
    foreach($badwords as $kb => $vb) {
        if (strstr($v, $kb)) $badwordfound = true;
        break;
    }
}
if ($badwordfound) { echo 'You\'re nasty!';}
else echo 'GoodGuy!';

Php check if string contains words in array

mickmackusa

39k11 gold badges76 silver badges112 bronze badges

answered Dec 10, 2012 at 6:08

GrabenGraben

2023 silver badges8 bronze badges

3

 $string = "This dude is a good man";   
 $bad = array('truck','shot','etc'); 
 $flag='0';         
 foreach($bad as $word){        
    if(in_array($word,$string))        
    {       
        $flag=1;       
    }       
}       
if($flag==1)
  echo "Exist";
else
  echo "Not Exist";

answered Feb 11, 2015 at 9:15

Php check if string contains words in array

JasperJasper

3455 silver badges9 bronze badges

2

How do you check if a string contains a word in an array?

To check if a string contains a substring from an array:.
Use the Array. some() method to iterate over the array..
Check if the string contains each substring..
If the condition is met, the string contains a substring from the array..

How do you check if a array contains a specific word in PHP?

Answer: Use the PHP strpos() Function You can use the PHP strpos() function to check whether a string contains a specific word or not. The strpos() function returns the position of the first occurrence of a substring in a string.

How do you find if an array contains a specific string in PHP?

Approach: In order to search an array for a specific value, we will be using the in_array() function where the parameter for the search is of string type & its value is set to true. Otherwise, this function returns a false value if the specified value is not found in an array.

How do you check if a string contains a substring PHP?

You can use the PHP strpos() function to get the position of the first occurrence of a substring in a string. The function will return false if it cannot find the substring.