Jack Maessen
Jack Maessen

Reputation: 1864

how to skip empty lines from a txt file with php

I am using this code to delete an email address form a txt file named database-email.txt:

// unsubscribe
if (isset($_POST['email-unsubscribe'])) {     
$emailToRemove = $_POST['email-unsubscribe'] . ',';
$content = file_get_contents('database-email.txt');
if($content = str_replace($emailToRemove, '',  $content)) {
    echo "$emailToRemove successfully removed!";
}
else {
    echo "$emailToRemove could not be removed!";
}
file_put_contents('database-email.txt',  $content);
}

?>

My txt file looks like this:

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

[email protected],
[email protected],

[email protected],

I tried this to skip all the empty lines in the txt file but without success:

file_put_contents('database-email.txt',  implode(PHP_EOL, file($content, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES)));

How can i skip the empty lines from database-email.txt ?

Upvotes: 0

Views: 2370

Answers (3)

dhinchliff
dhinchliff

Reputation: 1194

Use the file() function with FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES options to read the file as an array. Then use the array_search() function to search for the element and remove it if it's present. You can then implode the array and write it back to file.

Don't use your str_replace approach, it's buggy. Imagine this is your file:

[email protected]

If you remove [email protected] you will get:

ab

You are not checking that you are replacing an entire email.

I would also suggest that you remove the commas, you don't need them if you have only one email per line.

Upvotes: 3

Tommaso Belluzzo
Tommaso Belluzzo

Reputation: 23685

This should do the trick:

file_put_contents('database-email.txt', implode('', file($content, FILE_SKIP_EMPTY_LINES)));

Alternatively:

file_put_contents('database-email.txt',preg_replace('~[\r\n]+~',"\r\n",trim($content)));

Upvotes: 1

Syscall
Syscall

Reputation: 19778

You could try something like this :

file_put_contents('database-email.txt',
    str_replace("\n\n", "\n", file_get_contents('database-email.txt'))
);

NB \n depends of how you inserts lines in your file. It could be \r\n or PHP_EOL.

Upvotes: 1

Related Questions