我希望能够写入文件并始终在该行写入。
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/