Jump to content

How do i Replace a specific line in a text file using PHP?


davocold

Recommended Posts

how do i replace a specific line in a text file with an array string?

 

example:

 

text content is like this:

 

red,brown,green,black

black,green,red,brown

green,black,brown,red

 

so if i have $array = "purple,grey,pink,cyan";

 

how can i use fwrite to replace line 2 in text file which is green,black,brown,red with $array

 

i want to replace the whole line 2 with the arrray string.

Link to comment
Share on other sites

Something like this (Untested):

 

$line = 1; // Change to the line you want to replace (0 is the first line)
$array = "purple,grey,pink,cyan";
$file = "myfile.txt";
$handle = fopen($file, "r");
$contents = fread($handle, filesize($file));
fclose($handle);

$arrCont = explode("\n", $contents);
$arrCont[$line] = $array;
$handle = fopen($file, "w+");
fwrite($handle, implode("\n", $arrCont));
fclose($handle);

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.