使用PHP将字符串插入TXT文件的中间 [英] Inserting a string into the middle of a TXT file with PHP

查看:93
本文介绍了使用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);
?>

但是,这似乎不太优雅,尤其是开始记录文件内容的switch变量.我认为有比我的解决方案更好的方法.有吗?

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?

谢谢您的帮助.

推荐答案

用新行将文件分解.

这将给您每行一个不错的数组.

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将字符串插入TXT文件的中间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆