php - 在 PHP 中的特定行的开头添加文本

标签 php text line addition

我想知道如何使用 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/

相关文章:

php - 如何使用 PHP 和 MySQL 在搜索中显示 "No results"?

Three.js 放置一个通过直线垂直的平面

browser - 超文本咖啡壶控制协议(protocol)

python - 从 tkinter 中的文本小部件复制格式化文本

ruby - 如何根据 Ruby 中的单词列表有效地检查文本?

android - achartengine - 不同点和线的不同颜色

algorithm - 线相交横向

javascript - textarea 中的输入不显示为输入的内容

php - 广告词 API : Using campaigns and ads from live on the sandbox

php - 忽略 PDO 主机