Results 1 to 6 of 6
Thread: Edit a file
Jun 11, 2009, 04:26 #1
Edit a file
Please excuse if similar query has been posted earlier.
I have text file in which I have to search a word and replace it with a new word.
First I do is to get the file contents with fopen,then read the contents , maintain a string $newcontent that holds the contents of file ,the moment i get my word,replace it with new word in the string $newcontent
After that I write the whole string $newcontent to file again.
What I want is to just while scanning the file,the moment I find my word,replace it with new word there only instead of rewriting the whole file again.
Jun 11, 2009, 04:59 #2
As far as I know, you can't. But... I don't know everything
So let's see what others have to say.
Jun 11, 2009, 07:23 #3
$fname = "test.txt";
$lines = file($fname);
$out = "";
$pattern = '/ddd+/';
$replacement = 'replace';
foreach ($lines as $line)
$out .= preg_replace($pattern, $replacement, $line);
$f = fopen($fname, "r+");
aaa bbb ccc ddd eee dddmy mobile portal
Jun 11, 2009, 07:51 #4
You still read, change and then rewrite the whole file though.
Jun 11, 2009, 07:59 #5
If the replacement string is the same length (in bytes) as the original, then you can just over-write the bytes. Otherwise, the best you can get away with is writing from the insertion point to the end of the file. The easiest would be just writing the entire file.Salathe
Software Developer and PHP Manual Author.
Jun 11, 2009, 08:37 #6
- Join Date
- Apr 2008
- North-East, UK.
- 3 Post(s)
- 0 Thread(s)
You could, read the file a character at a time, if you find your word, record the position, place your new word in at that position and start the process again from the last recorded position plus the length of the replacement word.