[英]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';
}
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.