在nl2br中只允许一个br

时间:2010-07-29 16:48:20

标签: php

我让我的网站成员在textarea上发布一些有关他们的信息。我使用函数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

但这是问题所在。我不想让人们在文本中使用多个输入(br),所以我该怎么办?

2 个答案:

答案 0 :(得分: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 :(得分:-1)

你可以这样做:

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