Search code examples
phpregexreddit

Format \n\n into \n and disable unique \n in PHP (a la reddit)


I'm looking to do the same thing for my website as I've seen on reddit. When you \n once, it will not work, you will have to do two \n\n to get one

I tried this :

$texte = preg_replace('#{\n}#', '', $texte);
$texte = preg_replace('#{\n}{\n}#', '\n', $texte);
$texte = nl2br($texte);

and it doesn't work... someone can help?


Solution

  • Try this:

    $texte = preg_replace('#(\r\n|\r)#', "\n", $texte);
    $texte = preg_replace('#\n(?!\n)#', ' ', $texte);
    $texte = preg_replace('#\n\n#', "\n", $texte);
    $texte = nl2br($texte);
    

    The first line normalizes line endings. The second replaces single \ns by a space. The third line replaces double \ns by a single one.