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. Quote Link to comment 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. Quote Link to comment 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. Quote Link to comment 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); Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.