使用 php 替换文本文件中的特定行,同时保留到文件的其余部分


Replace specific line in text file using php while preserving to rest of the file

我有以下文本文件和php代码,文本文件包含一些小变量,我希望能够从表单中更新特定变量。

问题在于,当代码在提交时执行时,它会向文本文件添加额外的行,以防止从文本文档中正确读取变量。我在下面添加了文本文件、代码和结果。

文本文件:

Title
Headline
Subheadline
extra 1
extra 2

PHP代码:

<?php
session_start();
// Get text file contents as array of lines
$filepath = '../path/file.txt';
$txt = file($filepath); 
// Check post
if (isset($_POST["input"]) && 
    isset($_POST["hidden"])) {
    // Line to edit is hidden input
    $line = $_POST['hidden'];
    $update = $_POST['input'];
    // Make the change to line in array
    $txt[$line] = $update; 
    // Put the lines back together, and write back into text file
    file_put_contents($filepath, implode("'n", $txt));
    //success code
    echo 'success';
} else {
    echo 'error';
}
?>

编辑后的文本文件:

Title edited
Headline
Subheadline
extra 1
extra 2

期望的结果:

Title edited
Headline
Subheadline
extra 1
extra 2

由于Cheery和Dagon,有两种解决方案。

解决方案一

<?php
session_start();
// Get text file contents as array of lines
$filepath = '../path/file.txt';
$txt = file($filepath); 
//check post
if (isset($_POST["input"]) && 
    isset($_POST["hidden"])) {
    $line = $_POST['hidden'];
    $update = $_POST['input'] . "'n";
    // Make the change to line in array
    $txt[$line] = $update; 
    // Put the lines back together, and write back into txt file
    file_put_contents($filepath, implode("", $txt));
    //success code
    echo 'success';
} else {
    echo 'error';
}
?>

解决方案二

<?php
session_start();
// Get text file contents as array of lines
$filepath = '../path/file.txt';
$txt = file($filepath); 
// Get file contents as string
$content = file_get_contents($filepath);
//check post
if (isset($_POST["input"]) && 
    isset($_POST["hidden"])) {
    $line = $_POST['hidden'];
    $update = $_POST['input'] . "'n";
    // Replace initial string (from $txt array) with $update in $content
    $newcontent = str_replace($txt[$line], $update, $content);
    file_put_contents($filepath, $newcontent);
    //success code
    echo 'success';
} else {
    echo 'error';
}
?>