search

Home  >  Q&A  >  body text

Split a string into multiple lines by newlines.

<p>I have a string with newlines. I want to convert this string into an array and for each newline character, skip one index position in the array. <br /><br />If the string is: </p><p><br /></p> <pre class="brush:php;toolbar:false;">My text1 My text2 My text3</pre> <p>The result I want is this:</p> <pre class="brush:php;toolbar:false;">Array ( [0] => My text1 [1] => My text2 [2] => My text3 )</pre> <p><br /></p>
P粉014293738P粉014293738516 days ago545

reply all(2)I'll reply

  • P粉420958692

    P粉4209586922023-08-07 13:34:48

    I have been using this with great success:

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

    With the last \r, thanks @LobsterMan):

    reply
    0
  • P粉391955763

    P粉3919557632023-08-07 00:15:31

    You can use the explode function and use "\n" as the separator:

    $your_array = explode("\n", $your_string_from_db);

    For example, if you have the following code snippet:

    $str = "My text1\nMy text2\nMy text3";
    $arr = explode("\n", $str);
    var_dump($arr);

    You will get the following 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 Note that you must use a double-quoted string so that \n will be interpreted as a newline character. (See the man page for more details.)

    reply
    0
  • Cancelreply