Reputation: 767
I am new to PHP and I am practicing the file_put_contents() function, and I was wondering if this was possible.
I have a text file with the following copy:
--start placed content --
(content goes here)
--end placed content --
Is it possible to use file_put_contents to place the content inbetween the --start-- and --end-- lines. I have tried the FILE_APPEND flag, but it always places the content after the --end-- line. Or do I need to use file_get_contents first?
Thanks a lot, any help would be greatly appreciated.
Upvotes: 1
Views: 879
Reputation: 6919
You can retrieve the file as an array of lines, then insert the lines where you want, and when write it all back.
Similar example on this site by nathan: Write to specific line in PHP
Upvotes: 2
Reputation: 4421
No. The file needs to be read in and the data placed in the right place. You can do this with file_get_contents() to read to a string, and then use str_replace or preg_replace to replace the part between the markers with what you want, before using file_put_contents to write it back.
Upvotes: 3
Reputation: 454970
You can always do:
$data = '--start placed content --'.PHP_EOL.$data.'--end placed content --'.PHP_EOL;
file_put_contents($file,$data);
Upvotes: 2