سؤال

I just started using nl2br in my php site. Basically I am using it to give a nice layout to a 'bio' field in case the user presses enter.

Problem is that it stores the exact line break tag <br> in my database and it does the same when i display the same data from my server to a text area.

How can i prevent the textarea from displaying the actual <br> tag here's my sample code

//grabbing the data in the text area field
$bio = nl2br(htmlentities(trim($_POST['bio'])));

//displaying the value from the database
$row = mysql_fetch_array($my_select_query);
<textarea><?php echo $row['bio']?; ></textarea>

I get something that looks like this in my textarea Tesxt area result

how can i avoid this?

هل كانت مفيدة؟

المحلول

You shouldn't nl2br(), or even htmlentities() input before storing it in your database. I tend to keep it reasonably raw, which gives more scope to change things later on.

If this is already in production, you could create your own br2nl() function which reverses the effects of nl2br():

function br2nl($input) {
    return preg_replace('/<br\\s*?\/??>/i', '', $input);
}

نصائح أخرى

Use the nl2br function when showing the field on a page, not when editing. This way the field is stored with embedded line breaks instead of as a HTML fragment, which means it could be used also for other purposes.

Do not use nl2br to record information in the bank.

So when it is displayed it will respect the line breaks previously inserted in the text area.

//grabbing the data in the text area field
$bio = trim($_POST['bio']);

//displaying the value from the database
$row = mysql_fetch_array($my_select_query);
<textarea><?php echo $row['bio']?; ></textarea>
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top