doumei9832 2013-06-15 02:36
浏览 96
已采纳

使用PHP将字符串插入TXT文件的中间

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条回答 默认 最新

  • duanmangxie7131 2013-06-15 03:09
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?