3

我需要检查数组变量中的单词,我需要这样的东西:

$banned = array('word1','word2','word3','word4');


if (stristr($title, $banned) !== false) {

    //$title contains a banned word 

}else{

    //$title not contains any word of $banned variable array

}
4

4 回答 4

2
<?php
$banned = array('word1','word2','word3','word4');

$hit = false;
foreach ($banned as $banned_item)
{
    if (strpos($title, $banned_item) !== false)
    {
        $hit = true;
        break;
    }
}

if ($hit)
{
    // $title contains a banned word
}
else
{
    //$title not contains any word of $banned variable array
}

_

               ************** update1  ************** 

上面的代码是区分大小写的,如果你想让你的代码不区分大小写,只需更改:

  if (strpos($title, $banned_item) !== false)

至:

  if (stristr($title, $banned_item) !== false)
于 2013-07-22T07:12:13.967 回答
1

您需要不区分大小写的搜索,因此您需要遍历数组并将函数应用于每个元素:

<?php

$title = "text WORD3 text";
$banned = array('word1','word2','word3','word4');

$flag = 0;
foreach($banned as $word)
{
    if (stristr($title, $word) !== false) {
        $flag = 1;
        break;//no need to loop further
    }
}

if ($flag == 1)
{
    print "title contains a banned word";
}

印刷:

标题包含禁用词

于 2013-07-22T07:16:14.633 回答
-1

in_arrayPHP的使用函数

in_array($title, $banned)
于 2013-07-22T07:08:08.880 回答
-1

由于您不关心返回值,因此您可能希望使用stripos. stripos基本上是一样stristr的,但如果你的字符串包含在$title. stristr会匹配,然后返回

正如这里的其他一些答案所建议的那样,我会警告不要使用in_array,因为它只会在与您的禁用词之一完全匹配时才返回 true $title,而不是包含其中一个禁用词的长字符串。

$banned = array('word1','word2','word3','word4');

$found = false;

foreach($banned as $ban) {
    if( stripos($title, $ban) !== false ) {
        $found = true;
        break;
    }
}

if( $found ) {

    //$title contains a banned word 

}else{

    //$title not contains any word of $banned variable array

}
于 2013-07-22T07:09:15.703 回答