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

时间:2014-11-19 23:31:33

标签: php file text file-manipulation

我有以下文本文件和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

1 个答案:

答案 0 :(得分:3)

感谢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';
}
?>