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

时间:2015-03-21 12:51:31

标签: php line overwrite

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

我有一个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);

但是,这并不能取代特定的行。它将新字符串添加到一个新行上即可。我需要在该行上使用该特定行ERASED然后使用新字符串REPLACED。

我将如何继续这样做?我喜欢一些指示。

1 个答案:

答案 0 :(得分:0)

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