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

2019-01-01 10:08发布

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
)

18条回答
闭嘴吧你
2楼-- · 2019-01-01 10:51

StackOverflow will not allow me to comment on hesselbom's answer (not enough reputation), so I'm adding my own...

$array = preg_split('/\s*\R\s*/', trim($text), NULL, PREG_SPLIT_NO_EMPTY);

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...

$array = preg_split('/\s*\R/', rtrim($text), NULL, PREG_SPLIT_NO_EMPTY);

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...

$array = preg_split('/\s*\R\s*/', trim($text));

Or keeping both leading whitespace and empty lines...

$array = preg_split('/\s*\R/', rtrim($text));

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)...

$array = preg_split('/\R/', $text);
查看更多
呛了眼睛熬了心
3楼-- · 2019-01-01 10:51

Picked this up in the php docs:

<?php
  // split the phrase by any number of commas or space characters,
  // which include " ", \r, \t, \n and \f

  $keywords = preg_split("/[\s,]+/", "hypertext language, programming");
  print_r($keywords);
?>
查看更多
不流泪的眼
4楼-- · 2019-01-01 10:51

This method always works for me:

$uniquepattern="gd$#%@&~#"//Any set of characters which you dont expect to be present in user input $_POST['text'] better use atleast 32 charecters.
$textarray=explode($uniquepattern,str_replace("\r","",str_replace("\n",$uniquepattern,$_POST['text'])));
查看更多
孤独寂梦人
5楼-- · 2019-01-01 10:52

I've always used this with great success:

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

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

查看更多
栀子花@的思念
6楼-- · 2019-01-01 10:52

David: Great direction, but you missed \r. this worked for me:

$array = preg_split("/(\r\n|\n|\r)/", $string);
查看更多
只若初见
7楼-- · 2019-01-01 10:52

you can use this:

 \str_getcsv($str,PHP_EOL);
查看更多
登录 后发表回答