我想知道如何使用 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));"
如果要
每隔第二行添加一次,请使用此代码
$n = 0;
for ($i = 1; $i <= 10; $i++) {
if($n % 2 == 1) {
echo "Whatever Line: ".$i."<br>";
} else {
echo "Line ".$i."<br>";
} $n++;
}
但是,如果您只想添加第二行和第四行,请使用此代码。
for ($i = 1; $i <= 10; $i++) {
if(($i == 2) or ( $i == 4)){
echo "Whatever Line: ".$i."<br>";
} else {
echo "Line ".$i."<br>";
}
}