用php覆盖文本文件中的特定行


Overwrite a specific line in a text file with php

需要找到以下问题的简单解决方案:

我有一个php文件,当它被执行时,应该能够用一行不同的值替换它自己内部的特定代码行。

到目前为止,我想到了这个:

$file = "file.php";
$content = file($file); 
foreach($content as $lineNumber => &$lineContent) {
    if($lineNumber == 19) {
        $lineContent .= "replacement_string";
    }
}
$allContent = implode("", $content);
file_put_contents($file, $allContent);

然而,这并不能取代特定的行。它在新行上添加新字符串,就这样。我需要删除特定的行,然后用该行上的新字符串替换。

我该如何继续这样做?我想要一些指点。

由于file()创建了一个数组,因此可以使用索引来选择行。不要忘记数组索引从0开始!

$file = "file.php";
$content = file($file); 
$content[19] = "replacement_string'r'n";
$allContent = implode("", $content);
file_put_contents($file, $allContent);

您的问题是$lineContent .= "replacement_string";行中的.=。只需使用=或使用str_replace()str_ireplace()函数。