Replace 1 Line in A Text File with PHP

Posted on 2004-11-06
Last Modified: 2006-11-17
Greetings fellow ee'ers:

I have a text file called "data.txt".  Each line contains information about a user in the following format:

user<=>elvis<*>state<=>Minnesota<*>foo<=>foobar   (\n)
user<=>elvis2<*>state<=>Minnesota<*>foo<=>foobar   (\n)
user<=>elvis3<*>state<=>Minnesota<*>foo<=>foobar   (\n)

Given a user value I need to replace the contents of 1 line.  Example....

given: user=elvis2, change

user<=>elvis2<*>state<=>Minnesota<*>foo<=>foobar   (\n)
user<=>elvis2<*>state<=>Minnesota<*>foo<=>kittywumpus (\n)

#1) Read text file into a string, save as data2.txt then rename
#2) Delete the appropriate line (?) and append the file
#3) Clear the file (?) and write the string
#4) ????

Question by:djlurch
    LVL 2

    Expert Comment

    I would read it in to an array of strings, one string per line.

    Then I would edit the string to reflect the changes, probably by rebuilding the string...

    $file = "/path/to/file/data.txt";
    $fileline = file($file);
    $newfile = array();
    $newuserdata = array();
    foreach ($fileline as $thisline)
       $datapair = explode("<*>",$thisline); // Now each data pair is in an array.
       $userdata = explode("<=>",$datapair[0]); // Get the username as $userdata[1]
       $statedata = explode("<=>",$datapair[1]); // get the state as $statedata[1]
       //   ... and so on for all data pairs  //
       if ($userdata[1] == $desireduser)  // We have the user we want...
          $userdata[1] = $newuserdata;
          $statedata[1] = $newstate;
          $otherdata[1] = $newotherdata;
          // ... rewrite values for all data pairs //
          $newuserdata[0] = implode("<=>",$userdata);
          $newuserdata[1] = implode("<=>",$statedata);
          $newuserdata[2] = implode("<=>",$otherdata);
          // ... re-implode the info into the data pairs again. //
          $thisline = implode("<*>",$newuserdata);
          // We're back to having "thisline", but now it contains the new data.
       // No else line, because others are not having changes made.  
       $newfile[$i] = $thisline;
       $i += 1;

    You can write the file out as the file is being read, or you can read it all in to an array (as in my example) and then itterate through the array and write each line.  There may be a function to write ALL lines in an array to a file too... check for that kind of thing.

    But you see what I did... I broke up file line by line.  I broke up the lines in to data pairs.  I checked to see if this line's user info matched the desired user we're changing... if so, I rewrote all of the VALUES in the data pairs to equal the new values needed... then I reconstructed the pairs from the parts, reconstructed the line from the pairs... and put the line back in to the file. :)

    Basically, ripped it apart, and put it back together again. :)
    LVL 1

    Author Comment


    Nice code :)  Actually I have that part covered.  It the file manipulation that I'm looking for.  Thoughts?
    LVL 2

    Accepted Solution

    I'd just open a new file, overwriting the old one (instead of appending) and rewrite all of the lines.

    Or... alternatively... as you go through data.txt line by line, write to newdata.txt line by line after any changes are made (writing each line as you're still looping)... then when you're done, unlink("data.txt") and do a move of newdata.txt to data.txt. :)

    If you really want to be snazzy, you can make a backup of data.txt to data.bak (overwriting any existing data.bak) and THEN doing a file COPY of newdata.txt to data.txt. :)

    For info on outputting to a file:

    Or you can use:

    That may be the preferred way...

    Open the file

    Loop while reading from one file, do the fwrite to the new file

    Once done looping, close the new file.

    Make sure you preserve \r\n and such...

    Then see
    for info on how to copy files. :)
    LVL 1

    Author Comment

    Nice.  Thanks!

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    How your wiki can always stay up-to-date

    Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
    - Increase transparency
    - Onboard new hires faster
    - Access from mobile/offline

    The Client Need Led Us to RSS I recently had an investment company ask me how they might notify their constituents about their newsworthy publications.  Probably you would think "Facebook" or "Twitter" but this is an interesting client.  Their cons…
    Introduction Many web sites contain image galleries; a common design for these galleries includes a page with a collection of thumbnail images.  You can click on each of the thumbnail images to see the larger version of the image.  This is easily i…
    The viewer will learn how to dynamically set the form action using jQuery.
    The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

    737 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    22 Experts available now in Live!

    Get 1:1 Help Now