Forum Moderators: coopster

Message Too Old, No Replies

modifying a plain text file

         

guille

1:26 am on May 17, 2007 (gmt 0)

10+ Year Member



Hi, i have a text file with (ID - client name) like this:

01-bill
02-matt
03-john
04-martin

I want to open this file, search for the id (ie. "03") and change the name "john" for another. How can i do this? How can i change an entirely line and save the results?

Thanks in advance.

dreamcatcher

7:06 am on May 17, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi guille,

Use file [uk3.php.net] to read the text file into an array, then loop through the data. When you find a match, make the change, then clear the original text file and write the new data. As you have a hyphen (-), you can use that as a delimiter to explode the data on the loop.

So, something like this:

$replace_id = '03';
$replace_string = 'Fred';
$write_string = '';

$file = file('file.txt');

for ($i=0; $i<count($file); $i++)
{
$line = explode("-",$file[$i]);

if ($line[0]==$replace_id)
{
$write_string = $line[0].'-'.$replace_string."\n";
}
else
{
$write_string .= $line[0].'-'.$line[1]."\n";
}

}

Then clear the original file and write the new one:


unlink('file.txt');
$fp = fopen('file.txt', 'ab');

if ($fp)
{
fwrite($fp,trim($write_string));
fclose($fp);
}

Hope that helps.

dc