Question

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?

Was it helpful?

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.

OTHER TIPS

$str = preg_replace('~(*BSR_ANYCRLF)\R(\R?)~', '$1', $str);

\R with the (*BSR_ANYCRLF) option matches any CRLF type newline sequence (drop the option to match all Unicode newlines).

\R(\R)? will result in $1 = '\R' with two newlines and $1 = '' with one newline.


The above though will drop the newline entirely if you have only one. This is probably not what you want. Instead I would suggest leaving single newlines alone and converting double newlines to HTML <br /> tags:

$str = preg_replace('~(*BSR_ANYCRLF)\R{2}~', '<br />', $str);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top