【问题标题】:Overwrite a specific line in a text file with php用php覆盖文本文件中的特定行
【发布时间】:2015-05-24 19:55:20
【问题描述】:

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

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

但是,这不会替换特定的行。它将新字符串添加到新行上,就是这样。我需要该特定行已擦除,然后在该行上用新字符串替换。

我将如何继续这样做?我希望得到一些指点。

【问题讨论】:

  • 您为什么要这样做?将您的数据存储在数据库甚至文本文件中,但不要修改您正在执行的脚本。或任何其他脚本。
  • 这听起来是巨大安全问题的基础......
  • 这种方法也无法扩展。它只适用于合理的小文件。因为您将整个文件保存在内存中,实际上一次保存 2 次。
  • file() 使用后的第 19 行?为什么不尝试更改第 18 个索引

标签: php line overwrite


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-19
    • 2010-09-19
    • 2019-05-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多