Allow only one br in nl2br

I allowed my members of my website to post some information about them in the text box. I use a function nl2brto make it more beautiful, smth like:

$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 the problem. I don’t want people to use more than one input (br) allowed in the text, so what can I do?

+3
source share
2 answers

Why not just replace more than one newline before calling nl2br?

If you want to allow them to use only one new line in your message:

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

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

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

You can do:

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

Source: https://habr.com/ru/post/1757184/


All Articles