Jump to content

replace lines in a txt file


The Little Guy

Recommended Posts

Is it possible to replace one line in a textfile?

say I have these lines:

 

ray:house:1-21-2007_0224PM

joe:hoose:1-26-2007_0224PM

tim:hoooe:1-22-2007_0224PM

him:hoooo:1-20-2007_0224PM

 

If joe decides to log in, I need to update the time, or the 3rd "field" in the text file.

 

if I can not replace one line, what would the best way to do this?

 

P.S.

This is homework, and I cannot use a database for it.

Link to comment
https://forums.phpfreaks.com/topic/39536-replace-lines-in-a-txt-file/
Share on other sites

Use file() to read the data.

 

Create an array where the first element of each line is the key and the rest of the line is the value.

 

Update the array, using 'Joe' as the key to find the data.

 

Rewrite the array to the file.

try:

$array = file("text.txt");
foreach ($array as $line) {
$parts = explode(":", $line);
$times[] = $parts[0];}
$linenum = array_keys($times, "joe");//joe as an example
$data = file("text.txt");
$data[$linenum] = "modified";//changing the info.
$handle = fopen($file, "w");
foreach ($data as $val) {$write = fwrite($handle, $val);}
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.