【问题标题】:Replace specific line in text file using php while preserving to rest of the file使用php替换文本文件中的特定行,同时保留文件的其余部分
【发布时间】:2015-01-17 16:38:21
【问题描述】:

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

【问题讨论】:

  • implode("", $txt) 因为$txt 的每个原始元素末尾都已经有一个新的行符号。只需将它也添加到您自己插入的元素中。 $txt[$line] = $update . "\n"; 或者您可以使用PHP_EOL 代替"\n"(取决于具体情况)
  • @Cheery 谢谢,效果很好!
  • 只使用 str_replace 会快得多

标签: php file text file-manipulation


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-01
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多