Many situations we want to be able to detect if a post/comment is spam by checking to see if it contains a list of spam/forbidden words. The following provides a PHP function spamCheck which takes the content and will return true if the text contains any of the forbidden words.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <?php $SPAMWORDS = [ "SpamWord1", "SpamWord2", ]; function containsWord($str, $word) { return !!preg_match('#\\b' . preg_quote($word, '#') . '\\b#i', $str); } function spamCheck($content) { global $SPAMWORDS; foreach ($SPAMWORDS as $w) { if (containsWord($content, $w)) { return true; } } return false; } |
<?php $SPAMWORDS = [ "SpamWord1", "SpamWord2", ]; function containsWord($str, $word) { return !!preg_match('#\\b' . preg_quote($word, '#') . '\\b#i', $str); } function spamCheck($content) { global $SPAMWORDS; foreach ($SPAMWORDS as $w) { if (containsWord($content, $w)) { return true; } } return false; }
We can define the list of spam words, and the text searching is based on regex (regular expression) – and it will match the word boundary only meaning the “HelloWorld” won’t match word “Hello” or “World” but “Hello World” will match.
–EOF (The Ultimate Computing & Technology Blog) —
GD Star Rating
loading...
222 wordsloading...
Last Post: Teaching Kids Programming - Unobstructed Buildings Algorithm via Monotonous Decreasing Stack
Next Post: Simple and Efficient C Program to Compute the Mathematic Constant E (Euler's number)