Insert a line in the middle of a TXT file using PHP

There are several topics to this, but I could not find any connection with inserting text into an unordered text file after the specified (unique) point without changing any other file (I apologize if I missed this).

My code, how it seems to work:

if($file=fopen('dadada.txt','r+')) { echo 'File opened'; $switch=0; //This variable will indicate whether the string has has been found. $back=0; //This counts the number of characters to move back after reaching eof. } while(!feof($file)) { $string=fgets($file); if($switch==1) { $back+=strlen($string); $modstring=$modstring.$string; } if(strpos($string,'thing to find')!==FALSE) { echo 'String found'; $switch=1; $string=fgets($file); $modstring='test'.$string; $back+=strlen($string); } } $back*=-1; fseek($file,$back,SEEK_END); fwrite($file,$modstring); fclose($file); ?> 

But it seems rather inelegant, especially the switch variable, to start writing the contents of the file. I guess there is a much better way to do this than my solution. There is?

Thank you for your help.

0
source share
1 answer

Expand the file in a new line.

This will give you a nice array with each row.

Scroll and find the insertion point and add the text you want to add.

Then put it back and write to the file back.

0
source

Source: https://habr.com/ru/post/1276944/


All Articles