【问题标题】:Inserting a string into the middle of a TXT file with PHP使用 PHP 将字符串插入到 TXT 文件的中间
【发布时间】:2013-06-15 11:09:39
【问题描述】:

关于这个有几个线程,但我找不到任何处理在指定(唯一)点之后将文本插入无序文本文件的方法,而不修改文件的任何其余部分(如果我错过了)。

就目前而言,我的代码似乎可以工作:

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);
?>

但这似乎很不优雅,尤其是开始记录文件内容的开关变量。我认为有比我的解决方案更好的方法来做到这一点。有吗?

感谢您的帮助。

【问题讨论】:

    标签: php text insert


    【解决方案1】:

    用新行分解文件。

    这将为您提供每行的漂亮数组。

    循环查找插入点并添加要添加的文本。

    然后将其内爆并回写到文件中。

    【讨论】:

    • 我什至没有想过用换行符来分解整个文件,但是换行符是对文本进行排序的一件事。这比我的代码好得多。谢谢。
    • PHP 只能读写和追加到文本文件。如果您想在其他任何地方添加文本,那么最后您必须在变量中读取它,修改变量并将其写回。为了使事情更简单,通常用新线爆炸是一个很好的选择。 \r\n、\r 或 \n 取决于文件的行尾类型。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多