php - 写入文件中的特定行

标签 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);
}

最佳答案

让我们重写您的函数:

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

然后我们把“蜜蜂”放在我们想要的行上:

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

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

关于php - 写入文件中的特定行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30769299/

相关文章:

php - MySQL查询从A中选择行并组合B中的多行

php - 为什么这个 Mysql 查询不起作用

php - 使用 PDO 连接到远程 MYSQL 服务器会导致相同的错误 SQLSTATE[HY000] [2002]

php - REST API,成功和错误的数据返回方式

PHP函数获取数组中最后插入的数据

javascript - 如何在用户登录标题后隐藏某些内容

PHPExcel 创建电子表格的时间过长

php - 如何在 Twig 模板中拆分字符?

php - 内部服务器错误 500,运行 Yii 时出现内存不足错误

javascript - 是否可以将数据从本地存储保存到数据库mssql