I have a string with line breaks in my database. I want to convert that string into an array, and for every new line, jump one index place in the array.
If the string is:
My text1
My text2
My text3
The result I want is this:
Array
(
[0] => My text1
[1] => My text2
[2] => My text3
)
StackOverflow will not allow me to comment on hesselbom's answer (not enough reputation), so I'm adding my own...
This worked best for me because it also eliminates leading (second \s*) and trailing (first \s*) whitespace automatically and also skips blank lines (the PREG_SPLIT_NO_EMPTY flag).
-= OPTIONS =-
If you want to keep leading whitespace, simply get rid of the second \s* and make it an rtrim() instead...
If you need to keep empty lines, get rid of the NULL (it is only a placeholder) and PREG_SPLIT_NO_EMPTY flag, like so...
Or keeping both leading whitespace and empty lines...
I don't see any reason why you'd ever want to keep trailing whitespace, so I suggest leaving the first \s* in there. But, if all you want is to split by new line (as the title suggests), it is THIS simple (as mentioned by Jan Goyvaerts)...
Picked this up in the php docs:
This method always works for me:
I've always used this with great success:
(updated with the final \r, thanks @LobsterMan)
David: Great direction, but you missed \r. this worked for me:
you can use this: