I have a program which keeps a record of users in a flat text file DB. I need to locate a specific line of data, based on a key field identifier, and replace the entire line with a different line of data. In other words, I wish to swap one line with another. The new line must remain in the same position as the one it replaces.
Each line of data is a single record that contains 21 fields, delimited by pipe. The last field $field[20] is the identifier.
SAMPLE DB
Billy Bob|1234 Hillbilly Way|Loudholler|TN|37024||123-456-6789|blah@blah.com||Category 1|BIG TEST TO SEE IF THIS WORKS!|This is a test.|02/12/2010|0|ok|billywilly|60||||101
Dan Boone|4321 Coon Skin Road|Whoopass|KY|43265||123-456-6789|abig@coon.com||Category 4|NUTHER TEST TO SEE IF THIS WORKS!|This is a nuther test.|01/18/2010|0|ok|boonbaby|60||||102
David Crocket|2468 Hillbilly Way|Whoowee|VA|37024||123-456-6789|davey@whatever.com||Category 6|FINAL TEST TO SEE IF THIS WORKS!|This is a final test.|01/06/2010|0|ok|pocketrocket|60||||103
Here is the simple code I now use to locate and display a line based on key identifier.
<?php
$key = "102"; //key identifier for field 20
//Below is a sample replacement line
$replacestring = "Willy Nilly|4250 Hounddog Blvd|Plains|GA|54234||123-456-6789|Who@whatwhen.com||Category 4|REPLACE TEST TO SEE IF THIS WORKS!|This is a replacement test.|02/28/2010|0|ok|rogerwilco|60||||120";
$handle = fopen("data.txt", "r");
While (!feof($handle)){
$line = fgets($handle);
$field = explode('|', trim($line));
$gluedfield = implode("|", $field);
if($key ==$field[20]) {
echo "$gluedfield\n";
}
}
?>
I would appreciate any assistance that you might be able to offer on this. Thank you!
(By the way, no suggestions about the preferable use of mySQL is necessary. I already use DB's elsewhere, but it is not available for this particular script. )