Checking if any of the strings in an array matches a string
I'm trying to find out if a string matches any of my bad words in my array IE:
$badWords = Array('bad', 'words', 'go', 'here');
$strToChec开发者_StackOverflow中文版k = "checking this string if any of the bad words appear";
if (strpos($strToCheck, $badWords)) {
// bad word found
}
the issue is strpos can only check for a string and not an array, is there a method of doing this without looping through the array of badwords?
Not exactly, since all solutions inevitably must loop over your array, even if it's "behind the scenes". You can make a regular expression out of $badWords, but the runtime complexity will probably not be affected. Anyway, here's my regex suggestion:
$badWordsEscaped = array_map('preg_quote', $badWords);
$regex = '/'.implode('|', $badWordsEscaped).'/';
if(preg_match($regex, $strToCheck)) {
//bad word found
}
Note that I've escaped the words to protect against regex-injections, if they contain any special regex characters such as /
or .
array_intersect() gives you the list of matching words:
if (count(array_intersect(preg_split('/\s+/', $strToCheck), $badWords))) {
// ...
}
in_array.
Read question wrong.
Simplest implementation is to call strpos() for each of the badwords:
<?php
$ok = TRUE;
foreach($badwords AS $word)
{
if( strpos($strToCheck, $word) )
{
$ok = FALSE;
break;
}
}
?>
Try This..
$badWords = array('hello','bad', 'words', 'go', 'here');
$strToCheck = 'i am string to check and see if i can find any bad words here';
//Convert String to an array
$strToCheck = explode(' ',$strToCheck);
foreach($badWords as $bad) {
if(in_array($bad, $strToCheck)) {
echo $bad.'<br/>';
}
}
the above code will return all matched bad words, you can further extend it to implement your own logic like replacing the bad words etc.
精彩评论