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

Link to comment
Share on other sites

Oops... forgot. Bash will return 0 on success. I know it looks wrong but this will work.

 

<?php
  
  $file = "nameoffile.txt";
  $r = exec("sed -i -e 's/Dog/Horse/' $file");
  if ($r == 0) {
    echo "Horse replaced Dog";
  }

?>

Link to comment
Share on other sites

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.