开发者

Allow only one br in nl2br

开发者 https://www.devze.com 2023-01-09 16:12 出处:网络
I let my members of my website to post some information about them in textarea. I use function nl2br to be it more prettier, smth like that:

I let my members of my website to post some information about them in textarea. I use function nl2br to be it more prettier, smth like that:

$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 mo开发者_开发知识库re then one enter (br) allowed in text, so what can I do?


Why not just replace more than one new line away prior to calling nl2br?

If you want to let them use only one new line at all in their post:

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

If you want to let them use only one consecutive new line (allowing foo\nbar\nbaz):

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


You could do:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号