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

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

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

Post 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.
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post 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);
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post 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:
Post Reply