Matching a list of words with a sentence
I have a list of "bad" words having around 450 words in it.
I'm trying to check the sentence for it with
<?php
$sentence = "A quick brown fox jumps over the lazy dog";
foreach($words as $word) {
$check = strstr($sentence,$word);
i开发者_C百科f(!empty($check))
return false;
}
return true;
?>
Is there a faster and better approach to this?
You could try using a preg_split
and array_intersect
<?php
$sentence = "A quick brown fox jumps over the lazy dog";
$sntce_wrds = preg_split('/\s+/', $sentence);
return count(array_intersect($sntnce_words, $words)) > 0;
I think preg_replace should fit your needs as well. Pass the $words array as the pattern and space as the replacement. Then match the result with the original string. For e.g
$newStr = preg_replace($words, '', $sentence);
if($newStr !== $sentence)
return false;
return true;
Let know if this helps.
Edit: As pointed out by stillstanding, the words in the $words array need to be valid regexes. So this method would only work if the words are changed to patterns like "one" to "/one/".
Edit-2 : If you want to for some reason preserve the words array, then use
$wordArr = preg_replace("/(.*)/", '/\1', $words);
to convert all words to valid regexes. I think even with this overhead, it should be faster than strstr on a long list.
精彩评论