Forum Moderators: coopster

Message Too Old, No Replies

Insert a line of text into a file above a line containing a string

         

whitenoise

1:36 pm on Mar 25, 2015 (gmt 0)

10+ Year Member Top Contributors Of The Month



I wonder if you guys could help me with something. I have a text file which I use the following code to open a text file and append a line at the top.

$filename = $_SERVER["DOCUMENT_ROOT"]."/test.txt";
$content = "this is a test";

$handle = fopen($filename, 'r');
$content .= fread($handle,filesize($filename));
fclose($handle);
$handle = fopen($filename, 'w+');
fwrite($handle, $content,strlen($content));
fclose($handle);


Works fine. However I now need to insert the same line, but at a certain place in the text file. So say for example in the text line it contains a line "ABCD". I would want to insert my new line into the text file above the "ABCD" line.

I've tried a few things but haven't been able to get it to work. Can you help? Thanks :)

topr8

4:11 pm on Mar 25, 2015 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



probably not the most elegant way, but you could use str_replace

write your file content to a variable and then

str_replace( $file_content , 'ABCD' , 'new line text \n ABCD' );

then just save that as the file.

lucy24

7:20 pm on Mar 25, 2015 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Is "ABCD" literal text or a pattern? Can you be absolutely certain the text and/or pattern will occur only once-- or, at least, that the bit you want to change is always the first occurrence?

whitenoise

3:02 pm on Mar 27, 2015 (gmt 0)

10+ Year Member Top Contributors Of The Month



I adapted your idea topr8, and managed to get it to work, thanks.

Just for reference Lucy, the ABCD was just a representation of a line of text I was looking to literally replace. It would be a unique line for example "this is the line I am looking for", so would the only one and first instance in the file. Thanks for your input anyway, appreciated.