Jump to content

What's the best way to modify one line in a file?


php_joe

Recommended Posts

I want to write a snipit that will modify one line in a text file without changing any of the other lines.

 

I was thinking something like this:

<?
$newline = "new junk";
$linenumber = "3";
$file = "./textdocument.txt";
$line = file($file);
foreach($line as $key => $value){
if($key == $linenumber) $value = $newline;
}
$newcontent = implode("\n", $line);
$handle = fopen($file, "w");
fwrite($handle, $newcontent);
fclose($handle);
?>

 

Have I made a hash of this?

 

Is there a better way of doing it?

Maybe without exploding, looping, imploding, and rewriting all the lines?

 

Thanks in advance!

 

Joe

Correct me if I'm wrong, but that searches for a line based on the text in the line, right?

 

I want to single out a line by the line number and replace the text with the new text (the line # is the info I have, not the existing text).

 

This is what I've trimmed it down to so far:

<?
$line = file($textdocument);
$line[$line_number] = "$new_text\n";
$newcontent = implode("", $line);
$handle = fopen($worldlist, "w");
fwrite($handle, $newcontent);
fclose($handle);
?>

 

And it seems to work now. :D

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.