php explode new lines content from a txt file
Asked Answered
D

3

15

I have txt file with email addresses under under the other like :

[email protected]
[email protected]

So far I managed to open it with

 $result = file_get_contents("tmp/emails.txt");
but I don't know to to get the email addresses in an array. Basically I could use explode but how do I delimit the new line ? thanks in advance for any answer !
Dorris answered 18/7, 2010 at 9:5 Comment(1)
The answers below are ideal; but for reference, you could use explode with the newline character, represented as \n. (This may also be \r\n depending on whether you're using Windows or Linux).Gregorygregrory
S
37

Just read the file using file() and you'll get an array containing each line of the file.

$emails = file('tmp/emails.txt');

To not append newlines to each email address, use the FILE_IGNORE_NEW_LINES flag, and to skip empty lines, use the FILE_SKIP_EMPTY_LINES flag:

$emails = file('tmp/emails.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

Doing a var_dump($emails) of the second example gives this:

array(2) {
  [0]=>
  string(13) "[email protected]"
  [1]=>
  string(14) "[email protected]"
}
Seoul answered 18/7, 2010 at 9:8 Comment(1)
THough this works, it doesn't take into account windows based new lines. using preg_split works more reliably.Urina
C
12
$lines = preg_split('/\r\n|\n|\r/', trim(file_get_contents('file.txt')));
Collimore answered 6/5, 2013 at 10:44 Comment(0)
R
2

As crazy as this seems, doing a return or enter inside a double-quote ("") delimits a newline. To make it clear, type in:

explode("", "Stuff to delimit");

and simply hit return at the middle of "", so you get:

explode("

", "stuff to delimit");

and it works. Probably unconventional, and might only work on Linux. But it works.

Retuse answered 16/10, 2012 at 20:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.