问题描述:

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
网友答案:

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 ***
网友答案:

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.

相关阅读:
Top