How to put string in array, split by new line?


Question

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
)
1
196
1/10/2017 12:50:49 PM

Accepted Answer

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)

258
9/27/2009 12:31:37 PM

I've always used this with great success:

$array = preg_split("/\r\n|\n|\r/", $string);

(updated with the final \r, thanks @LobsterMan)


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon