PHP 替换文件中的多行

PHP replacing multiple lines in a file

我可以选择文件的一行(例如 dummy.php)并将其替换为存储在名为 [=13 的变量中的文本=] 但我想选择几行并用几个变量替换它们。例如:

$site_name 第二行,

$URL 第 4 行,

$protocol 第 6 行,

$author 第 8 行,

$description 第 10 行

还有 $currentdate 第 12 行。

我编写了这段代码,它替换了第二行:

        $currentdate = date('d F Y');
$filename = getcwd() . "/dummy.php"; 
$date_line = 1; 
$lines = file( $filename , FILE_IGNORE_NEW_LINES ); 
$lines[$date_line] =    "$currentdate";
file_put_contents( $filename , implode( "\n", $lines ) );

我再问一遍,那好几行怎么加几个变量呢? 这个问题给出了示例变量和行号。 另外,我做了一个代码,但我不知道它是否有效。我无法尝试将此代码添加到我的项目文件中,因为我害怕让我的代码变得更糟并禁用其他代码,这些代码也位于该页面中。 这是未经测试的代码:

$site_name_line = 1; 
$URL_line = 3; 
$protocol_line = 5; 
$author_line = 7; 
$description_line = 9; 
$currentdate_line = 11;
$lines = file( $filename , FILE_IGNORE_NEW_LINES ); 
$lines[$site_name_line] =   "$site_name";
$lines[$URL_line] = "$URL";
$lines[$protocol_line] =    "$protocol";
$lines[$author_line] =  "$author";$lines[$description_line] =   "$description";$lines[$currentdate_line] =  "$currentdate";
file_put_contents( $filename , implode( "\n", $lines ) );
/**
 * Replace lines with given content.
  *
  * $substitutions array should look
  * [
  *   1 => "new first line content",
  *   4 => "new fourth line content",
  * ]
  *
  * @param string $filename
  * @param array $substitutions
  */
  function replaceLines($filename, array $substitutions) {
     $lines = file($filename);

     foreach ($lines as $lineNumber => $lineContent) {
         if (isset($substitutions[$lineNumber])) {
             $lines[$lineNumber] = $substitutions[$lineNumber];
         }
     } 

     file_put_contents($filename, $lines);
 }

当然,这不会处理所有可能的边缘情况,例如,当您无权访问该文件或您在替换数组中提供不存在的行时。

我自己找到了答案。我没有想到,我可以。但我做到了。这是整个 PHP 代码:

<?php
if (isset($_POST['post'])){

// GET EMAIL
        $site_name = $_POST["site_name"];
        $URL = $_POST["URL"];
        $protocol = $_POST["protocol"];
        $author = $_POST["author"];
         $description = $_POST["description"];
        $currentdate = date('d F Y');
$filename = getcwd() . "/dummy.php"; 
$site_name_line = 1; 
$URL_line = 3; 
$protocol_line = 5; 
$author_line = 7; 
$description_line = 9; 
$currentdate_line = 11;
$lines = file( $filename , FILE_IGNORE_NEW_LINES ); 
$lines[$site_name_line] =   "$site_name";
$lines[$URL_line] = "$URL";
$lines[$protocol_line] =    "$protocol";
$lines[$author_line] =  "$author";$lines[$description_line] =   "$description";$lines[$currentdate_line] =  "$currentdate";
file_put_contents( $filename , implode( "\n", $lines ) );
}
?>