dukevin dukevin - 3 years ago 97
PHP Question

Efficient way to test string for certain words

I have a bunch of banned words and want to check if string A contains any of these words.

For example:

$banned_words = "dog cat horse bird mouse monkey blah blah2 blah3 "; //etc
$string_A = "The quick brown fox jumped over the lazy dog";

How can I efficiently check to see if any of the words in the string match up with any of the words in the banned words list?

Answer Source
if (preg_match('~\b(' . str_replace(' ', '|', $banned_words) . ')\b~', $string_A)) {
    // there is banned word in a string
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download