Page 1 of 1

Locate a string in file and replace it with a new string.

Posted: Wed Apr 21, 2004 6:01 pm
by Chris Corbyn
Hi,

How can I locate a string in for example file.txt and then replace it with a new string then save the file?

So if I had
red_green_blue,
orange_green_black,
violet_blue_pink,
which was added by fwrite the line "someline, \r\n" and I wanted swap the bit orange_green_black, (written as "orange_green_black, \r\n") for apples_oranges_pears, how could I do it?

I figured I could use str_replace somehow but I still don't know how I can get the file as a string (including the new line attributes \r\n) and replace a bit then save it leaving all else unchanged.

Any help much appreciated.

Posted: Wed Apr 21, 2004 6:05 pm
by Weirdan

Code: Select all

$string = implode('',file($filename));
$string = str_replace('orange_green_black','apples_oranges_pears',$string);
$fp = fopen($filename,"w");
fwrite($fp, $string);
fclose($fp);

Posted: Wed Apr 21, 2004 6:14 pm
by Chris Corbyn
Brilliant. That works perfectly. I still need to get my head around all the file functions. I know it's not that complicated but it's just one those things I'm struggling with. Lol :-) :oops: