Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explode text into array as per paragraph

I have the following text:

$test = 'Test This is first line

Test:123

This is Test';

I want to explode this string to an array of paragraphs. I wrote the following code but it is not working:

$array = explode('\n\n', $test);

Any idea what I'm missing here?

like image 993
Deep123 Avatar asked Jan 28 '26 12:01

Deep123


1 Answers

You might be on Windows which uses \r\n instead of \n. You could use a regex to make it universal with preg_split():

$array = preg_split('#(\r\n?|\n)+#', $test);

Pattern explanation:

  • ( : start matching group 1
  • \r\n?|\n : match \r\n, \r or \n
  • ) : end matching group 1
  • + : repeat one or more times

If you want to split by 2 newlines, then replace + by {2,}.


Update: you might use:

$array = preg_split('#\R+#', $test);

This extensive answer covers the meaning of \R. Note that this is only supported in PCRE/perl. So in a sense, it's less cross-flavour compatible.

like image 69
HamZa Avatar answered Jan 31 '26 01:01

HamZa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!