Search code examples
phpfilefopenstr-replace

How to str_replace a txt file with newlines using PHP


I have a text file with the following 2 lines

woof
woof99

I then have this code where it's supposed to take the username, example woof and take it out and replace it with nothing.

$file = fopen("../UsersProfile/".$MyUsername."/otherfiles/Following.txt","a") or die("Unable to open file");
    $content = file_get_contents("../UsersProfile/".$MyUsername."/otherfiles/Following.txt");
    $newcontent = str_replace($Username."\n", '', "$content");
    file_put_contents("../UsersProfile/".$MyUsername."/otherfiles/Following.txt", "$newcontent");
    fclose($file); 

the text file will then look like this with one line now.

woof99

the issue that I am having is that it isn't working for some reason. I believe it worked before but for some reason now it isn't. Is there an easier way to do this? Thanks!

Edit: I found out what I needed to do I need to do \r\n


Solution

  • $newcontent = str_replace($Username."\n", '', $content);
    

    Just turn this "$content" to this $content :D