Reputation: 391
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?
Upvotes: 2
Views: 8502
Reputation: 76395
The easiest way to get this text into an array like you describe would be:
preg_match_all('/.+/',$string, $array);
Since /./
matches any char, except for line terminators, and the +
is greedy, it'll match as many chars as possible, until a new-line is encountered.
Using preg_match_all
ensures this is repeated for each line, too. When I tried this, the output looked like this:
array (
0 =>
array (
0 => '$test = \'Test This is first line',
1 => 'Test:123',
2 => 'This is Test\';',
),
)
Also note that line-feeds are different, depending on the environment (\n
for *NIX systems, compared to \r\n
for windows, or in some cases a simple \r
). Perhaps you might want to try explode(PHP_EOL, $text);
, too
Upvotes: 1
Reputation:
You need to use double quotes in your code, such that the \n\n
is actually evaluated as two lines. Look below:
'Paragraph 1\n\nParagraph 2'
=
Paragraph 1\n\nParagraph 2
Whereas:
"Paragraph 1\n\nParagraph 2"
=
Paragraph 1
Paragraph 2
Also, Windows systems use \r\n\r\n
instead of \n\n
. You can detect which line endings the system is using with:
PHP_EOL
So, your final code would be:
$paragraphs = explode(PHP_EOL, $text);
Upvotes: 1
Reputation: 14921
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 timesIf 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.
Upvotes: 7
Reputation: 2406
Your code
$array = explode('\n\n', $test);
should have \n\n
enclosed in double quotes:
$array = explode("\n\n", $test);
Using single quotes, it looks through the variable $test
for a literal \n\n
. With double quotes, it looks for the evaluated values of \n\n
which are two carriage returns.
Also, note that the end of line depends on the host operating system. Windows uses \r\n
instead of \n
. You can get the end of line for the operating system by using the predefined constant PHP_EOL
.
Upvotes: 2