Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to delete a single line in a txt file with php

Tags:

php

unlink

i was wondering if it is posible to delete a single line in a txt file with php.

I am storing emailadresses in a flat txt file named databse-email.txt

I use this code for it:

<?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:

<form action="" method="POST">
   <input name="email-subscribe" type="text" />
   <input type="submit" name="submit" value="Subscribe">
</form>

The content of the file looks like this:

[email protected],
[email protected],
[email protected],
[email protected],
[email protected],
[email protected],
[email protected],
[email protected],

All lines are , seperated

Lets say i want to delete only the emailadres: [email protected]

How can i do that?

What i want to achieve is a unsubscribe form and delete a single line in the .txt file

like image 875
Jack Maessen Avatar asked Dec 11 '22 08:12

Jack Maessen


1 Answers

You can use str_replace

$content = file_get_contents('database-email.txt');
$content = str_replace('[email protected],', '', $content);
file_put_contents('database-email.txt', $content);
like image 139
Mojo Allmighty Avatar answered Dec 30 '22 23:12

Mojo Allmighty