我想知道用php删除txt文件中的单行是否可行。
我将电子邮件存储在名为databse-email.txt
我使用此代码:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$email = $_POST['email-subscribe'] . ',' . "\n";
$store = file_put_contents('database-email.txt', $email, FILE_APPEND | LOCK_EX);
if($store === false) {
die('There was an error writing to this file');
}
else {
echo "$email successfully added!";
}
}
?>
形式:
<form action="" method="POST">
<input name="email-subscribe" type="text" />
<input type="submit" name="submit" value="Subscribe">
</form>
该文件的内容如下所示:
janny@live.nl,
francis@live.nl,
harry@hotmail.com,
olga@live.nl,
annelore@mail.ru,
igor@gmx.de,
natasha@hotmail.com,
janny.verlinden@gmail.com,
所有行都,
分开
假设我想只删除电子邮件:igor@gmx.de
我该怎么做?
我想要实现的是取消订阅表单,并在.txt
文件中删除一行
答案 0 :(得分:4)
您可以使用In [146]: x = np.linspace(-1000, 1000, 10**6)
In [147]: x.shape
Out[147]: (1000000,)
In [148]: vf = np.vectorize(f)
In [149]: %timeit [f(i) for i in x]
1.46 s ± 5.42 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
In [150]: %timeit vf(x)
1.03 s ± 8.73 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
str_replace
答案 1 :(得分:3)
由于文件系统的工作方式,您无法以直观的方式执行此操作。您必须使用除要删除的行之外的所有行覆盖该文件,这是一个示例:
$emailToRemove = "igor@gmx.de";
$contents = file('database-email.txt'); //Read all lines
$contents = array_filter($contents, function ($email) use ($emailToRemove) {
return trim($email, " \n\r,") != $emailToRemove;
}); // Filter out the matching email
file_put_contents('database-email.txt', implode("\n", $contents)); // Write back
这是一个流式替代解决方案,适用于文件不适合内存的情况:
$emailToRemove = "igor@gmx.de";
$fh = fopen('database-email.txt', "r"); //Current file
$fout = fopen('database-email.txt.new', "w"); //New temporary file
while (($line = fgets($fh)) !== null) {
if (trim($line," \n\r,") != $emailToRemove) {
fwrite($fout, $line, strlen($line)); //Write to new file if needed
}
}
fclose($fh);
fclose($fout);
unlink('database-email.txt'); //Delete old file
rename('database-email.txt.new', 'database-email.txt'); //New file is old file
还有一种方法可以就地执行此操作,以最大限度地减少所需的额外磁盘,但这更棘手。
答案 2 :(得分:1)
您可以通过编程方式执行此操作,只查看每一行,如果不是您要删除的内容,则会将其推送到将写回文件的数组中。如下所示
$DELETE = "igor@gmx.de";
$data = file("database-email.txt");
$out = array();
foreach($data as $line) {
if(trim($line) != $DELETE) {
$out[] = $line;
}
}
$fp = fopen("database-email.txt", "w+");
flock($fp, LOCK_EX);
foreach($out as $line) {
fwrite($fp, $line);
}
flock($fp, LOCK_UN);
fclose($fp);
答案 3 :(得分:1)
删除特殊词,然后删除空白行,请尝试以下操作:
parent.component.html
答案 4 :(得分:0)