Search code examples
phppreg-matchstr-replacefile-readend-of-line

Unable to remove end of line characters in PHP


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?


Solution

  • 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