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

时间:2012-12-10 06:00:07

标签: php arrays string compare

这是一个聊天页面。我有$string = "This dude is a mothertrucker"。我有一系列坏词:$bads = array('truck', 'shot', etc)。如何查看$string是否包含$bad中的任何字词? 到目前为止,我有:

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

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

12 个答案:

答案 0 :(得分:59)

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

答案 1 :(得分:11)

1)最简单的方法:

if ( in_array( 'eleven',  array('four', 'eleven', 'six') ))
...

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

答案 2 :(得分:9)

你可以试试这个而不是你的代码

$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 :(得分:4)

您可以翻转坏字数组并更快地执行相同的检查。将每个坏词定义为数组的键。例如,

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

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

答案 4 :(得分:2)

一旦发现任何不好的词语,就会退出或退出,就像这样

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

答案 5 :(得分:1)

想要这个?

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

答案 6 :(得分:0)

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

$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!';

答案 7 :(得分: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";

答案 8 :(得分:0)

有一个非常简短的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';
}

单行:

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

完成所有工作。

答案 9 :(得分:0)

如果您想使用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;
}

答案 10 :(得分:-1)

您也可以通过这种方式进行过滤

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

答案 11 :(得分:-4)

您最好的选择应该是在客户端运行此代码,即仅在JavaScript可用时运行

const fruits = ["Banana", "Orange", "Apple", "Mango"];
const check  = fruits.includes("Mango")
//  console.log(check)

它返回true,因为芒果在数组中。如果芒果不在数组中,它将返回false

不是PHP,严格用于JavaScript(客户端)