允许nl2br中只存在一个br标签

3

我允许我的网站成员在文本框中发布一些关于自己的信息。为了使其更美观,我使用了nl2br函数,类似于这样:

$text_of_area = nl2br($_POST['text_area_name']); //yeah, of course i use functions against xss, sql injection attacks

mysql_query("..."); //here I insert a text

But here is problem. I don't want to allow people to use more then one enter (br) allowed in text, so what can I do?

2个回答

6

在调用nl2br之前,为什么不直接替换掉多个换行符呢?

如果你想让用户在发布内容时只使用一个换行符:

$firstPos = strpos($text, "\n");
if ($firstPos !== false) {
    $text = substr_replace(array("\r","\n"),'', $text, $firstPos + 1);
}
$text = nl2br($text);

如果您想让他们仅使用一个连续的新行(允许foo\nbar\nbaz):

$text = preg_replace('#[\r\n]+#', "\n", $text);
$text = nl2br($text);

-1

你可以这样做:

$text_of_area = nl2br(str_replace("\r\n", "\n", $_POST['text_area_name']));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接