Search code examples
phparraysexplode

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?


Solution

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