nl2br()函数广告<br>如果在/下一行之后没有输入字符[复制]

This question already has an answer here:

I am using nl2br function with str_replace as follows:

$data = (!empty($_POST['content']))?nl2br($_POST['content']):null;
$data_fix = str_replace(array("", "
"), '', $data);

When I insert data into database next lines automatically receives a <br>. Okay fine. To 95% extent this is what I want. But if there is no character entered after the next line in <textarea> it still enters a <br>.

Example:

What I want:

Hello Stackoverflow!<br>I am new here.
(new line space eliminated)

What I get:

Hellow Stactoverflow!<br>I am new here.<br>
(new line space inserted)

Please help me solve this!

</div>

trim() function will prevent adding extra <br> which are not needed if there is no text entered in or after the next line!

Simply replaced

$data = (!empty($_POST['content']))?nl2br($_POST['content']):null;

With

$data = (!empty($_POST['content']))?nl2br(trim($_POST['content'])):null;

And it did the job! But trim() should be after the nl2br() otherwise it won't work!

Answered my own question for future reference of other people seeking solution to the same!