I am having an issue with this bad word prevention code. If I leave it as is below the code will say "the word bad1 is not allowed" no matter what I type. If i remove the line 4th line below with the $entry variable, then the code lets everything pass, even bad1.
The goal is to match words like 'are', but not match 'care'
if (isset($_POST['text'])) {
// delete the line below in your code
$entry = "notbad1word bad1 bad notbad1.";
$disallowedWords = array(
'bad1',
'bad2',
);
foreach ($disallowedWords as $word)
{ // use $_POST['text'] instead of $entry
preg_match("#\b". $word ."\b#", $entry, $matches);
if(!empty($matches))
die("The word " . $word . " is not allowed. <b><a
href=\"javascript:history.back();\">Go Back</a></b>");
}
}
This code below works fine and was what I accepted originally as an answer (I can just stick with this but it won't do anything for interior matching I don't think). Anyway, if there isn't a quick fix, I will be content with the below answer that I originally accepted:
if (isset($_POST['text'])) {
// Words not allowed
$disallowedWords = array(
'bad1',
'bad2',
);
$pattern = sprintf('/(%s)/i', implode('|',$disallowedWords));
$subject = $_POST['text'];
if (preg_match($pattern, $subject, $token)) {
die(sprintf("The word '%s' is not allowed. <b><a
href=\"javascript:history.back();\">Go Back</a></b>
", $token[1]));
}
}