PHP:在文件的特定行之间插入内容?

时间:2017-11-03 01:03:33

标签: php file

想象一下,我有一个包含以下内容的TXT文件(some.txt):

data of first line
data of next line
#start-marker

data of next line
#end-marker
data of next line

我想在#start-marker

之后写一些行

目前,我有这个:

$fp = fopen('some.txt','r+');
$insertPos=0;
while (!feof($fp)) {
    $line=fgets($fp);
    if (strpos($line, '#start-marker')!==false) {
        $insertPos=ftell($fp);
}
fseek($fp,$insertPos);
fwrite($fp,'Data to be written');
fclose($fp);

但问题是:

data of first line
data of next line
#start-marker
Data to be written

新插入的行后,所有行都会消失。

怎么做?

预期产出:

data of first line
data of next line
#start-marker

Data to be written
data of next line
#end-marker
data of next line

2 个答案:

答案 0 :(得分:0)

$myfile = file_get_contents('some.txt');
$insert = '#start-marker blah blah blah new data here';
$myfile = str_replace('#start-marker', $insert, $myfile, 1);
file_put_contents('some.txt', $myfile);

答案 1 :(得分:0)

我认为您正在寻找附加档案。 尝试从“r +”更改为添加模式a+到您的代码:

$fp = fopen('some.txt','a+');
$insertPos=0;
while (!feof($fp)) {
    $line=fgets($fp);
    if (strpos($line, '#start-marker')!==false) {
        $insertPos=ftell($fp);
}
fseek($fp,$insertPos);
fwrite($fp,'Data to be written');
fclose($fp);

参考:模式参数 - http://php.net/manual/en/function.fopen.php