【问题标题】:How to amend or delete a line of a text file in php? [duplicate]如何在php中修改或删除文本文件的一行? [复制]
【发布时间】:2015-03-19 00:10:24
【问题描述】:

例如,我的几行学生信息记录很少:

AbuBaka Male
MaryLu Female
WongAhKao Male

如果我想删除文件中的MaryLu Female记录,变成:

AbuBaka Male
WongAhKao Male

如何做到这一点?如果我使用WW+,所有数据都会被清除。

【问题讨论】:

  • 你为什么要把它们保存在一个文本文件中?我们有这类东西的数据库。
  • 将文件读入数组,对数组进行修改,覆盖文件。

标签: php algorithm file


【解决方案1】:

由于只有值,您可以使用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)等数据库管理系统旨在规避您在将数据存储在文本文件中时遇到的问题。

但是由于我不知道您的用例,这只是一个警告,也许您的用例非常适合将名称存储在文本文件中。 :)

【讨论】:

    【解决方案2】:

    试试这个:

    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
    

    【讨论】:

    • @AhYong 你有预付款吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-06
    • 1970-01-01
    • 2013-08-12
    • 2021-03-24
    • 2021-03-11
    • 2012-07-22
    • 2012-09-11
    相关资源
    最近更新 更多