0

I am trying to remove the curse words from the comment entered by the user.The curse words are read from a text file, but the problem is that the words I read do not match the word it is meant to be. The apparent problem is the EOL Character(apparently), I used str_replace to replace all the EOL characters but it did not affect the outcome.

Here is my code:

while(!feof($myfile)){
    $array[$i]=fgets($myfile);
    $word=$array[$i];
    str_replace("\n","",$word,$count);
    echo $count;
    str_replace("\r","",$word,$cont);
    echo $cont;
    str_replace("\r\n","",$word,$con);
    echo $con;
    str_replace(" ","",$word,$co);
    echo $co;
    str_replace(PHP_EOL,"",$word,$c);
    echo $c;
    if($word==="anal")
    echo "afdsfdsa";
    $comment= str_replace($word,"****",$comment);

I downloaded the curse word text file from here I can't figure out what the problem is. Why aren't the two words matching?

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Shivam
  • 383
  • 1
  • 3
  • 8
  • You can just use $word = trim($word); to trim off any extra whitespace. Also note that str_replace is case sensitive. – kainaw Nov 17 '15 at 14:58

2 Answers2

0

To get each word, why not try:

$file = file_get_contents($myfile);
$words = explode(PHP_EOL, $file);
Ben
  • 8,894
  • 7
  • 44
  • 80
  • `PHP_EOL` is the newline used by your PHP setting, but the file can have a totally different newline. If `PHP_EOL` is `\n` and the newlines in the file are `\r\n`, after your `explode` each item (except the last) will have a trailing CR. – Casimir et Hippolyte Nov 17 '15 at 15:03
-2

Here's the revised code

$myfile = 'swearWords.txt';
$words=file_get_contents($myfile);
$array = explode(PHP_EOL,$words);
$comment = "f*** this s***";
$comment= str_replace($array,"Bleep",$comment);
echo $comment;

Output

​ Bleep this Bleep
Lucky Chingi
  • 2,248
  • 1
  • 10
  • 15
  • Yes this is correct, but what was wrong in the above code? – Shivam Nov 17 '15 at 15:13
  • @Shivam if you compare the code, you are getting the file contents inside the while loop, this will never end the loop. Secondly the file content is not an array, you convert it into an array based on a separator, in this case the new line feed. – Lucky Chingi Nov 17 '15 at 15:20
  • @LuckyChingi the while loop will end , and I agree with the 2nd part . – Shivam Nov 17 '15 at 16:18
  • BTW: [Blacklists don't work](https://blog.codinghorror.com/blacklists-dont-work/). Except for hilarity. – Deduplicator Nov 17 '15 at 16:48
  • Note to readers: the code is broken given the change from `"fuck"` to `"f***"` (see the [revision history](http://stackoverflow.com/posts/33760221/revisions)). You must change the contents of `$comment` to include an actual string from the swearWords file for this to work. – jscs Nov 17 '15 at 18:58