3

I'm trying to explode a string that has more than 1 newline. More specifically, 2 newlines, and I'm not sure how to do it. For example:

$text = "
text1

text2

text3
";

$text = explode(PHP_EOL, $text);

There would be some empty indexes in the array after this. I need to explode at 2 newlines instead of one. How do I do that?

jessica
  • 1,593
  • 1
  • 11
  • 29
  • 1
    You can also use [preg_split](http://php.net/manual/en/function.preg-split.php) with pattern `/\R{2}/` to match `\r\n\r\n` or `\n\n`. `$res = preg_split('/\R{2}/', trim($text));` [test at eval.in](https://eval.in/422565); See [this answer what \R matches](http://stackoverflow.com/a/18992691/3110638). – Jonny 5 Aug 26 '15 at 09:40

2 Answers2

6

If you are sure on how the newlines are formed (they may contain \n and/or \r), you can do it this way:

$Array = explode("\n\n", $text);

You can also trim the string, to remove newlines at the start and end:

$Array = explode("\n\n", trim($text));
Marcovecchio
  • 1,310
  • 9
  • 19
  • 3
    "\n" will not always be appropriate - either in files generated with a Windows editor (with OS settings), or when coming from an HTML form field. I recommend using preg_split in this case and accepting "\r?\n" as the newline pattern to be more accommodating (the "\n\r" and "\r" forms have drifted into obsolescence). – user2864740 Aug 26 '15 at 01:18
  • @user2864740, I have added an alert about newline variations, thanks. – Marcovecchio Aug 26 '15 at 01:22
3

This should work for you:

Just use preg_split() with the flag: PREG_SPLIT_NO_EMPTY set and explode the string with the constant PHP_EOL, e.g.

$arr = preg_split("/". PHP_EOL . "/", $text, -1, PREG_SPLIT_NO_EMPTY);
print_r($arr);

output:

Array ( [0] => text1 [1] => text2 [2] => text3 )
Rizier123
  • 56,111
  • 16
  • 85
  • 130