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

最后都变了- 提交于 2019-12-23 03:11:09

问题


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?


回答1:


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.




回答2:


$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);


来源:https://stackoverflow.com/questions/7374565/format-n-n-into-n-and-disable-unique-n-in-php-a-la-reddit

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!