Search code examples
phpexplodeline-breaks

How to explode with double line break in PHP?


I want to explode a text to separate paragraphs and tried

$array = explode("\n\n", $str");

but it is not a practical approach since double line breaks can be in the form of

\n \n
\r\n\r\n

or other formats and \n\n is not always the case.

Is there a safe approach to explode double line breaks (or ideally all multi-line breaks)?


Solution

  • preg_split : regex explode

    $array = preg_split("/(\n\s\n){1,}|(\n){1,}|(\r\n){1,}/", $str);
    

    (\n\s\n){1,}: Line break, Space, Line break, unlimited combo.

    (\n){1,}: Line break, unlimited combo.

    (\r\n){1,}: Line break, unlimited combo.

    /: Enclosing the parameters with forward slash delminators.

    If you want to replace it with <br>: nl2br :

    $str = nl2br($str);