簡體   English   中英

如何在php中修改或刪除一行文本文件?

[英]How to amend or delete a line of a text file in php?

例如,我很少在幾行中記錄學生信息:

AbuBaka Male
MaryLu Female
WongAhKao Male

如果我想刪除文件中的MaryLu Female記錄,並成為:

AbuBaka Male
WongAhKao Male

怎么做? 如果我使用WW+ ,則所有數據將被刪除。

由於只有值,因此可以使用file()

例:

<?php

// Read all lines from a file to array
$users = file('users.txt',FILE_IGNORE_NEW_LINES);

// Search for the array id of the line we want to be deleted
$idToDelete = array_search('MaryLu Female',$users);

// Check if we have a result
if($idToDelete !== false){
    // If so, delete the array entry
    unset($users[$idToDelete]);
}

// Finally, put the remaining entries back into the file,
// overwriting any existing content.
file_put_contents("users.txt",implode(PHP_EOL,$users));

但是請注意,將數據存儲在文本文件中不是一個好主意。 原因之一是,一旦有兩個用戶使用您的腳本(假設腳本在Web服務器上運行),那么保存最后勝利的腳本就會被使用。

MySQL,MariaDB或PostgreSQL甚至SQLite(內置於php afaik中)之類的數據庫管理系統旨在避免將數據存儲在文本文件中時遇到的問題。

但是由於我不知道您的用例只是警告,所以您的用例對於將名稱存儲在文本文件中是非常好的。 :)

試試這個:

1.txt里面有:

AbuBaka Male
MaryLu Female
WongAhKao Male

PHP代碼:

<?php

$delete = 'MaryLu Female';
$array = file('1.txt', FILE_IGNORE_NEW_LINES);

$id = array_search($delete, $array);
array_splice($array, $id, 1);
$string = implode("\n", $array);

file_put_contents('2.txt', $string);

?>

在2.txt中,您將看到:

AbuBaka Male
WongAhKao Male

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM