Replace String In File (Pointers?)
Posted: Mon Jun 27, 2005 6:09 pm
I have a feeling the answer to this question is a little more complicated than I think. Here goes: Say I want to replace a string in a particular file. For the sake of examples, I guess, let's call the file quote.txt. Let's say quote.txt is made up of the text That's-a spicy meatball!. And (finally!) let's say I want to change "meatball" to "little number". So, I might do something like this, right?
Is that the gist? (No error checking and such, obviously...I'm just looking for the framework, here.)
So, as I understand it, once the script is done with $replace, it's holding the whole file, with 'meatball' changed to 'little number', correct?
If so, that's all well and good. But suppose quote.txt is a thousand or so lines long. I probably don't want to be kicking huge chunks of data around in variables like that, do I?
My question, then (I guess!), is: what's the best way to efficiently pick the word 'meatball' out of 1000+ lines of a file, and surgically replace it with 'little number'?
Code: Select all
$filename = 'quote.txt';
$handle = fopen($filename,'r+');
$file = fread($handle, filesize($filename));
$replace = str_replace('meatball','little number',$file);
fwrite($replace,$file);
fclose($handle);So, as I understand it, once the script is done with $replace, it's holding the whole file, with 'meatball' changed to 'little number', correct?
If so, that's all well and good. But suppose quote.txt is a thousand or so lines long. I probably don't want to be kicking huge chunks of data around in variables like that, do I?
My question, then (I guess!), is: what's the best way to efficiently pick the word 'meatball' out of 1000+ lines of a file, and surgically replace it with 'little number'?