jessica
jessica

Reputation: 1687

Exploding a string at 2 newlines as oppose to just 1

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?

Upvotes: 3

Views: 730

Answers (2)

Rizier123
Rizier123

Reputation: 59701

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 )

Upvotes: 3

Marcovecchio
Marcovecchio

Reputation: 1332

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

Upvotes: 6

Related Questions