我需要检查数组变量中的单词,我需要这样的东西:
$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
}
我需要检查数组变量中的单词,我需要这样的东西:
$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
}
<?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)
您需要不区分大小写的搜索,因此您需要遍历数组并将函数应用于每个元素:
<?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";
}
印刷:
标题包含禁用词
in_array
PHP的使用函数
in_array($title, $banned)
由于您不关心返回值,因此您可能希望使用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
}