如何在php中修改或删除一行文本文件?
例如,我在几行中几乎没有学生信息记录:如何在php中修改或删除一行文本文件?,php,algorithm,file,Php,Algorithm,File,例如,我在几行中几乎没有学生信息记录: AbuBaka Male MaryLu Female WongAhKao Male 如果我想删除文件中的MaryLu-Female记录,并成为: AbuBaka Male WongAhKao Male 怎么做?如果我使用W或W+,所有数据都将被擦除。尝试以下方法: 1.txt有以下内容: PHP代码: 因为只有值,所以可以使用 例如: <?php // Read all lines from a file to array $users = f
AbuBaka Male
MaryLu Female
WongAhKao Male
如果我想删除文件中的MaryLu-Female
记录,并成为:
AbuBaka Male
WongAhKao Male
怎么做?如果我使用W
或W+
,所有数据都将被擦除。尝试以下方法:
1.txt有以下内容:
PHP代码:
因为只有值,所以可以使用 例如:
<?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));
看在上帝的份上,你为什么要把它们保存在一个文本文件中?我们有这类东西的数据库。将文件读入数组,对数组进行更改,覆盖文件。@AhYong有进展吗?
<?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);
?>
AbuBaka Male
WongAhKao Male
<?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));