Here is my source
$Message = $_GET["message"];
$Username = htmlspecialchars($_GET["username"]);
$unix = ($_GET["time"]);
include 'mcheck.php';
$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);
echo $Message;
Say the bad word is go
and $Message = I Like to go to school
I want it to echo I Like to *** to school
but instead im getting
***I***Like***To******to***school***
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'));
using the 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 (\b
).
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.
For example:
\b(one|two|three)\b
i think yo need to remove empty fields from explode resulting array
Why don't you just use str_replace
Example
$badWords = array("go","school");
$message = " I like to go to school" ;
$newMessage = str_replace($badWords, "***", $message);
echo $newMessage ;
Output
I like to *** to ***
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.