Inserting a string into the middle of a TXT file w

2019-09-09 20:19发布

问题:

There are a few threads about this, but I couldn't find any that deal with inserting text into an unordered text file, after a specified(unique) point, without modifying any of the rest of the file(I apologize if I missed it).

My code, as it stands, 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 this seems pretty inelegant, particularly the switch variable to begin recording the contents of the file. I assume there is a much better way to do this than my solution. Is there?

Thank you for your help.

回答1:

Explode the file by new line.

That will give you a nice array with each line.

Loop through and find the point of insertion and add the text you want to add.

Then implode it back and write it to the file back.



标签: php text insert