检查字符串是否包含数组中的单词

时间:2022-09-08 01:44:38

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:

这是一个聊天页面。我有一个$ string =“这个家伙是一个mothertrucker”。我有一系列坏词:$ bads = array('truck','shot'等)。我怎么能检查$ string是否包含$ bad中的任何单词?到目前为止我有:

        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.

除非我这样做,当用户输入$ bads列表中的单词时,输出为NO!是的!所以由于某种原因,代码运行了两次。

10 个解决方案

#1


51  

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

#2


9  

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

#3


9  

1) The simplest way:

1)最简单的方法:

$yourWord='nine';
$targets = array("four", "eleven", "nine", "six");

if (in_array($yourWord, $targets)) {
    echo "FOUND!!";
}

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

2)另一种方式(在将数组检查到另一个数组时):

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

#4


3  

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.

在这段代码中,我们只是检查索引是否存在,而不是将坏词与坏词列表中的所有单词进行比较。 isset比in_array快得多,并且比array_key_exists快一点。确保坏字数组中的所有值都不设置为null。如果数组索引设置为null,则isset将返回false。

#5


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

#6


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<br>';
        }
        else {
            echo 'YES<br>';
        }
    }

#7


0  

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

如果聊天字符串不那么长,我会这样做。

$badwords = array('motherfucker', 'ass', 'hole');
$chatstr = 'This dude is a motherfucker';
$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 'Youre nasty!';}
else echo 'GoodGuy!';

#8


0  

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

#9


0  

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

有一个非常简短的PHP脚本,您可以使用它来识别使用str_ireplace的字符串中的坏词,如下所示:

$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.

完成所有工作。

#10


0  

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

如果你想使用array_intersect(),那么使用下面的代码:

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

#1


51  

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

#2


9  

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

#3


9  

1) The simplest way:

1)最简单的方法:

$yourWord='nine';
$targets = array("four", "eleven", "nine", "six");

if (in_array($yourWord, $targets)) {
    echo "FOUND!!";
}

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

2)另一种方式(在将数组检查到另一个数组时):

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

#4


3  

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.

在这段代码中,我们只是检查索引是否存在,而不是将坏词与坏词列表中的所有单词进行比较。 isset比in_array快得多,并且比array_key_exists快一点。确保坏字数组中的所有值都不设置为null。如果数组索引设置为null,则isset将返回false。

#5


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

#6


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<br>';
        }
        else {
            echo 'YES<br>';
        }
    }

#7


0  

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

如果聊天字符串不那么长,我会这样做。

$badwords = array('motherfucker', 'ass', 'hole');
$chatstr = 'This dude is a motherfucker';
$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 'Youre nasty!';}
else echo 'GoodGuy!';

#8


0  

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

#9


0  

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

有一个非常简短的PHP脚本,您可以使用它来识别使用str_ireplace的字符串中的坏词,如下所示:

$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.

完成所有工作。

#10


0  

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

如果你想使用array_intersect(),那么使用下面的代码:

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