简体   繁体   中英

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:

annelore@mail.ru,
francien@live.nl,
frans@moonen.nl,
harry@hotmail.com,

jannie@live.nl,
jeanette.schmitz@live.nl,

johnny.doe@live.nl,

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 ?

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 .

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)));

Use the file() function with FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES 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:

abdc@domain.com

If you remove dc@domain.com 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM