views:

1517

answers:

4

Hi, I have a string, with line breaks in my database.

I want to put that string in an array, and for every new line, jump one index place in the array.

If the string is:

"My text1(here is a line break)My text2(here is a line break)My text3"

The result I want is this:

array[0] = "My text1"

array[1] = "My text2"

array[2] = "My text3

+1  A: 

see http://docs.php.net/explode

$text = "My text1
My text2
My text3";
$x = explode("\n", $text);

The line break doesn't always have to be \n. It could also be \r\n (crlf, e.g. windows, parts of the http specification, ...) or even a single \r. If you have to deal with all of them at the same time you might be interested in preg_split.

VolkerK
+9  A: 

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)

Pascal MARTIN
Although it's simple, you explained it perfectly.
Daniel S
+1  A: 
explode("\n", $str);

The " (instead of ') is quite important as otherwise, the line break wouln't get interpreted.

Damien MATHIEU
A: 
<anti-answer>

As other answers have specified, be sure to use explode rather than split because as of PHP 5.3.0 split is deprecated. i.e. the following is NOT the way you want to do it:

$your_array = split(chr(10), $your_string);

LF = "\n" = chr(10), CR = "\r" = chr(13)

</anti-answer>
Tom