Jump to content

Cant remove string from file ?


adamh91

Recommended Posts

Hey, im trying to remove a string form a file, i tried using replace and replacing it with "", this dosen't work, ive set the chmod to the correct settings aswell, i cant see whats wrong with this.
[code]
$handle = fopen("usernames.txt","r+");
while (!feof($handle))
    {
$data = fgets($handle);
}
$data=str_replace($_GET["User"],"",$data);
fwrite($handle, $Data);
fclose($handle);
[/code]
thanks  ;D
Link to comment
https://forums.phpfreaks.com/topic/25084-cant-remove-string-from-file/
Share on other sites

fgets() will return *just* a line. You need fread() or better yet, file_get_contents() as it has much better performance. You will then need to decide how to update the text file with your new data.

I suggest you [b][i]read[/i][/b] [url=http://uk2.php.net/manual/en/ref.filesystem.php]PHP Filesystem Reference[/url]. (see what I did there? ;))

For future reference, always try to debug your variables to see if they are what you expect. Had you echo'ed the output of $data in your script, you would have seen it return just one line.
Thanks, i echoed the variable to test and it shows it without the string i want to replace, which is good.
but how can i write the new data to the file, i tried fwrite and file_put_contents, neither of them work, file_put says function unknown :S
any help?, thanks :D
Well that is the problem with using unstructured files.

Have another look at [url=http://http://uk2.php.net/manual/en/function.file-put-contents.php]file_put_contents[/url] it should accomplish what you need. Provided of course you are using PHP version 5?

Something along the lines of...
[code]
<?php

file_put_contents($filename, $newdata, LOCK_EX);

?>
[/code]

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.