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
)
For anyone trying to display cronjobs in a crontab and getting frustrated on how to separate each line, use explode:
using '\n' doesnt seem to work but chr(10) works nicely :D
hope this saves some one some headaches.
true array:
Embed Online:
An alternative to Davids answer which is faster (way faster) is to use
str_replace
andexplode
.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 secondMore detail and bencmark info on my forum
As other answers have specified, be sure to use
explode
rather thansplit
because as of PHP 5.3.0split
is deprecated. i.e. the following is NOT the way you want to do it:LF = "\n" = chr(10), CR = "\r" = chr(13)
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:
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.