Replace line in text file

A

Anonymous

Guest
way2real said:
I am trying to replace a line in a text file. The file is small (50-100 lines) and contains username:password pairs. I can identify the line based on the username. Is there a way I can read the file in to a variable and use preg_replace or do I have to read the file into an array and loop through that? I have tried readfile without success.

Thanks for any thoughts.

Mike

Hi Mike,
yes there is. Use the statements:

$contents = file ("yourFileName")

This returns an array of equal dimension as the number of the lines you have in your file. Thus you now need:

for ($i= 1; $i< sizeof($contents); $i++){

do your identification and replacement here

}

You now need to open your file for writing the results.
$fa = fopen("YourFileName", "a");

for ($i = 0; $i < sizeof($contents); $i++){
$fw = fwrite($fa, $contents[$i]);
}

fclose($fp);

And you ended.

Some comments though. You asked if you can just replace the line of interest without getting into the loops. To the best of my knowledge this cannot be done (unless you can open and edit the file in binary mode as I know it in VBasic) because the text files are opened for sequential access (usually). Thus we get the for loop.
Also note the bolded segments, which are the functions themselves that you can use to get the program. If you need any more information on their use, just copy, paste on the "search on PHP.net" service of this forum.

Hope this helps,
Manos
[/b]
 
Back
Top