Here is my source
$Message = $_GET["message"];
$Username = htmlspecialchars($_GET["username"]);
$unix = ($_GET["time"]);
$file1 = file_get_contents('filter.txt');
$bad_words = explode(PHP_EOL, $file1);
$compare = explode('', $Message);
foreach ($bad_words as $bad_word)
$Message = preg_replace('/\b('.$bad_word.')\b/i', "***", $Message);
Say the bad word is
$Message = I Like to go to school
I want it to
echo I Like to *** to school
but instead im getting
i dont know what the problem is
Your file most likely ends with a newline (which is a good thing: all text-files on *nix systems are supposed to), which means that the last element of
explode(PHP_EOL, $file1) is empty (it's everything between the last newline and the end of the file, which is nothing). I would recommend writing:
$file1 = trim(file_get_contents('filter.txt'));
trim function to eliminate that last newline.
Based on the output, you likely have an empty element in your array. So it's ultimately matching a word boundary (
To confirm this add the following to debug your code:
$bad_words = explode(PHP_EOL, $file1); print_r($bad_words);
As an aside, it's a waste to loop over each bad word. I suggest using a single regex with alterations once you've resolved the above.
Why don't you just use
$badWords = array("go","school"); $message = " I like to go to school" ; $newMessage = str_replace($badWords, "***", $message); echo $newMessage ;
I like to *** to ***
i think yo need to remove empty fields from explode resulting array
You should use
strtr for this purpose.
you can pass array with key=>replace, which will be somewhat more efficient that preg_replace
apart from that, must be bad badwords dic.