Newline Conversion in Submitted Text in PHP

时光总嘲笑我的痴心妄想 提交于 2019-12-01 19:39:12

The function you're using, nl2br is used for inserting them, but not replacing them. If you want to replace \n with <br /> you just need to use str_replace. Like so:

$string = str_replace("\n","<br />",$string);

There is absolutely no need for regex in this situation.

It seems like the problem you described is not a bug, but a feature of bl2br. You could just write your own function for it, like:

<?php
function NlToBr($inString)
{
    return preg_replace("%\n%", "<br>", $inString);
}
?>

I found this one in the comments of the documentation of the nl2br-function in the PHP Manual: http://php.net/manual/de/function.nl2br.php. If the one I posted did not work for you, there should be plenty more where it came from.

(Or just use the function from the other Answer that was just posted, I guess that should work, too)

This should fix it:

preg_replace('/<br(\s+)?\/?>(?!\s*\n)/i', "\n", mysql_result($result,$i,"content"))

You cannot simply remove the breaks, because they might be on the same line. This regex will replace all breaks with newline but not those that are followed by the newline.

It will leave the <br>\n in the text. Additional regex will get rid of them:

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