I need to check words in array variable, I need something like this:
$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 **************
The code above is case-sensitive, if you want your code be case-insensitive, just change:
if (strpos($title, $banned_item) !== false)
to:
if (stristr($title, $banned_item) !== false)
Use in_array
function of PHP
in_array($title, $banned)
Since you don't care about the return value, you probably want to use stripos
. stripos
is basically like stristr
, but it just returns true or false if your string is contained in $title
. stristr
would match, then return
I would caution against using in_array
, as some of the other answers here suggest, since it would only return true if $title
exactly matches one of your banned words, rather than it being a long string that contains one of the banned words.
$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
}
You want case insensitive search, so you need to loop through array and apply the function to every element:
<?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";
}
prints:
title contains a banned word