如何在 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