The Java String class has a split() method which splits the string around matches of the given regular expression. To split a string on newlines, you can use the regular expression '\r?\ n|\r' which splits on all three '\r\n' , '\r' , and '\n' .
Split a string at a newline character. When the literal \n represents a newline character, convert it to an actual newline using the compose function. Then use splitlines to split the string at the newline character. Create a string in which two lines of text are separated by \n .
The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.
join("\n") did exactly what you want.
I've always used this with great success:
$array = preg_split("/\r\n|\n|\r/", $string);
(updated with the final \r, thanks @LobsterMan)
You can use the explode
function, using "\n
" as separator:
$your_array = explode("\n", $your_string_from_db);
For instance, if you have this piece of code:
$str = "My text1\nMy text2\nMy text3";
$arr = explode("\n", $str);
var_dump($arr);
You'd get this output:
array
0 => string 'My text1' (length=8)
1 => string 'My text2' (length=8)
2 => string 'My text3' (length=8)
Note that you have to use a double-quoted string, so \n
is actually interpreted as a line-break.
(See that manual page for more details.)
A line break is defined differently on different platforms, \r\n, \r or \n.
Using RegExp to split the string you can match all three with \R
So for your problem:
$array = preg_split ('/$\R?^/m', $string);
That would match line breaks on Windows, Mac and Linux!
PHP already knows the current system's newline character(s). Just use the EOL constant.
explode(PHP_EOL,$string)
An alternative to Davids answer which is faster (way faster) is to use str_replace
and explode
.
$arrayOfLines = explode("\n",
str_replace(["\r\n","\n\r","\r"],"\n",$str)
);
What's happening is:
Since line breaks can come in different forms, I str_replace
\r\n, \n\r, and \r with \n instead (and original \n are preserved).
Then explode on \n
and you have all the lines in an array.
I did a benchmark on the src of this page and split the lines 1000 times in a for loop and:preg_replace
took an avg of 11 secondsstr_replace & explode
took an avg of about 1 second
More detail and bencmark info on my forum
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With