Create Bad Words Filter
An answer to this question on Stack Overflow.
Question
Hi please help me I am using this code to filter some words but the the problem is it doesn't match the exact word and in stead it just blocks words that contain the letters from my word.
For example: ".com" I type commander and the word gets blocked please help.
$badwords = explode('|', 'http|www|.com');
foreach($badwords as $badword)
{
if(preg_match("/$badword/", $post->data['message'], $match))
{
$post->errors['badwords']['error_code'] = "Warning message goes here";
}
}
Answer
The line you want is likely
preg_match("/\b$badword\b/i", $post->data['message'], $match))
The \b indicates a letter which cannot be used to form a word (see here). This prevents com from matching commander or datacom. The i at the end makes the search case-insensitive.
Also, keep in mind that using .com as one of your badwords may not have the effect you want. The period character (.) matches any single character in a regular expression. Rather, you want to search for (\.), which will actually match the period. (See here for more details on the period character.)
Finally, if you're trying to match URL's, you could check out this question.