写入文件中的特定行

时间:2015-06-10 23:54:05

标签: php

我希望能够写入文件并始终在该行写入。

1 Hello
2 How are you
3 Good
4 I see
5 Banana
6 End

使用功能:

function filewriter($filename, $line, $text,$append) {
}

所以append = add而不覆盖该行,这是可选的,因为它将默认附加

所以追加:

filewriter ("bob.txt", 2, "Bobishere", true) or filewriter ("bob.txt", 2, "Bobishere") 

输出:

1 Hello
2 Bobishere
3 How are you
4 Good
5 I see
6 Banana
7 End

但是如果它们没有附加,它看起来像这样:   filewriter(“bob.txt”,2,“Bobishere”,false)

输出:

1 Hello
2 Bobishere
3 Good
4 I see
5 Banana
6 End

我只是弄清楚如何覆盖文件或添加到文档的末尾。

目前的功能是什么:

function filewriter($filename,$line,$text,$append){
  $current = file_get_contents($filename);
  if ($append)
   $current .= $line;
  else
   $current = $line;
  file_put_contents($file, $current);
}

1 个答案:

答案 0 :(得分:0)

让我们改写你的功能:

function filewriter($filename,$line,$text,$append){
    $current = file_get_contents($filename);

    //Get the lines:
    $lines = preg_split('/\r\n|\n|\r/', trim($current));

    if ($append)
    {
         //We need to append:
         for ($i = count($lines); $i > $line; $i--)
         {
             //Replace all lines so we get an empty spot at the line we want
             $lines[$i] = $lines[i-1];
         }

         //Fill in the empty spot:
         $lines[$line] = $text;
    }
    else
         $lines[$line] = $text;

    //Write back to the file.
    file_put_contents($file, $lines);
}

<强>伪代码

该系统背后的逻辑是:

我们得到了一份清单:

[apple, crocodile, door, echo]

我们想在第2行插入bee。我们首先要做的是在第2行之后移动所有元素:

1: apple
2: crocodile
3: door
4: echo
5: echo //==> We moved 'echo' 1 spot backwards in the array

下一步:

1: apple
2: crocodile
3: door
4: door //==> We moved 'door' 1 spot backwards in the array
5: echo

然后:

1: apple
2: crocodile //==> This is a useless spot now, so we can put "bee" here.
3: crocodile //==> We moved 'crocodile' 1 spot backwards in the array
4: door
5: echo

然后我们把'#34; bee&#34;在我们想要的线上:

1: apple
2: bee //==> TADA!
3: crocodile 
4: door
5: echo

警告:PHP中的数组从零开始,因此第一行是行0。使用上述功能时请记住这一点!