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.

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);

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.