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

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,4073 gold badges17 silver badges18 bronze badges

asked Dec 10, 2012 at 6:00

user1879926user1879926

1,2633 gold badges13 silver badges24 bronze badges

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

Nirav RanparaNirav Ranpara

15.8k4 gold badges42 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

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

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

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

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

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

Irshad KhanIrshad Khan

5,2902 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!';

mickmackusa

38.8k11 gold badges76 silver badges111 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

JasperJasper

3455 silver badges9 bronze badges

2

Not the answer you're looking for? Browse other questions tagged php arrays string compare or ask your own question.

How do I find a word in an array PHP?

PHP in_array[] Function The in_array[] function searches an array for a specific value. Note: If the search parameter is a string and the type parameter is set to TRUE, the search is case-sensitive.

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 search for a word in an array?

You can use the includes[] method in JavaScript to check if an item exists in an array. You can also use it to check if a substring exists within a string. It returns true if the item is found in the array/string and false if the item doesn't exist.

How do you check if an array contains an element in PHP?

The in_array[] function is an inbuilt function in PHP that is used to check whether a given value exists in an array or not. It returns TRUE if the given value is found in the given array, and FALSE otherwise.

Chủ Đề