Board index   FAQ   Search  
Register  Login
Board index php forum :: php coding PHP coding => General

Replace line in text file

Ask about general coding issues or problems here.

Moderators: macek, egami, gesf

Re: Replace line in text file

Postby uncertain_manos » Wed Dec 18, 2002 11:37 pm

way2real wrote: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]
uncertain_manos
New php-forum User
New php-forum User
 
Posts: 31
Joined: Wed Oct 23, 2002 12:55 am

Return to PHP coding => General

Who is online

Users browsing this forum: No registered users and 2 guests

Sponsored by Sitebuilder Web hosting and Traduzioni Italiano Rumeno and antispam for cPanel.