The Little Guy Posted February 21, 2007 Share Posted February 21, 2007 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 More sharing options...
joquius Posted February 21, 2007 Share Posted February 21, 2007 You can use file(), and then search for the line with foreach or array_search or something and then rebuild the file with the edited line. Link to comment https://forums.phpfreaks.com/topic/39536-replace-lines-in-a-txt-file/#findComment-190781 Share on other sites More sharing options...
Barand Posted February 21, 2007 Share Posted February 21, 2007 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. Link to comment https://forums.phpfreaks.com/topic/39536-replace-lines-in-a-txt-file/#findComment-190800 Share on other sites More sharing options...
ted_chou12 Posted February 22, 2007 Share Posted February 22, 2007 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); Link to comment https://forums.phpfreaks.com/topic/39536-replace-lines-in-a-txt-file/#findComment-191170 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.