我想知道如何使用 PHP 在 txt 文件中的特定行的开头添加文本。
例如第 2 行和第 4 行:
Line 1
Line 2
Line 3
Line 4
至
Line 1
Whatever Line 2
Line 3
Whatever Line 4
编辑:每行的内容始终是可变的,因此我无法使用替换或搜索特定单词。
谢谢:)
最佳答案
使用file()
获取文件的内容,每行作为返回数组的索引:
$lines = file('path/to/your/file');
然后您可以使用正确的行索引执行您需要的任何操作:
// prepend content to line 2:
$abc = 'abc' . $lines[1];
// append content to line 4:
$xyz = $lines[3] . 'xyz';
整个过程(获取内容,更新内容,然后替换原始文件):
$file = 'yourfile.txt';
$lines = file($file);
$lines[1] = 'xxx' . $lines[1]; // prepend content to line 2.
$lines[3] = 'yyy' . $lines[3]; // prepend content to line 4.
file_put_contents($file, implode('', $lines));"
关于php - 在 PHP 中的特定行的开头添加文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27347353/