|
Posted by Hans 'pritaeas' Pollaerts on 07/19/06 09:43
Hi. Please note that preg_replace() can contain arrays for the bad words and
their counterparts, and process them in one go.
$badwords = array ("/\bbad1\b/i", "/\bbadder2\b/i", "/\bverybad3\b/i");
$replacements = array ("****", "*******", "********");
$filetext = file_get_contents ("test.txt");
$newfiletext = preg_replace ($badwords, $replacements, $filetext);
$file_put_contents ("test2.txt", $newfiletext);
Of course you can build the badwords and replacements arrays using any
technique you like. You can read them from file or db.
Hans
"Mike" <mike@mjfcadsolutions.co.uk> wrote in message
news:1153297410.067289.145410@p79g2000cwp.googlegroups.com...
> I have developed a script to filter swear words by reading a text file
> that contains swear words and replace it with **** as follows...
>
> test.txt:
>
> bad1
> bad2
> bad3
> anotherbad2
>
> filter.php:
>
> <?php
> $textarea = "bad1 anotherbad2 bad3";
> $filename = "test.txt";
> $fp = fopen($filename, "r") or die("File not there");
> while (!feof($fp)) {
> $line = fgets($fp, 1024);
> $wordlen = strlen(trim($line));
> $count = 1;
> $newword = "";
> while ($count <= $wordlen) {
> $newword .= "*";
> $count++;
> }
> echo "Line = $line<br>";
> echo "New Line = $newword<br>";
> $textarea = preg_replace('/\b'.$line.'\b/i', $newword, $textarea);
> }
> echo $textarea;
> ?>
>
> Below is the output I get....
>
> Line = bad1
> New Line = ****
> Line = bad2
> New Line = ****
> Line = bad3
> New Line = ****
> Line = anotherbad2
> New Line = ***********
> bad1 *********** bad3
>
> For some reason it only does the replace on the last work in the list
> within test.txt, in this case "anotherbad2".
>
> I update $textarea after every line in the while loop so I don't
> understand.
>
> Can anyone help?
>
> Thanks
>
> Mike
>
Navigation:
[Reply to this message]
|