Question

I have a form with a textarea where users can write about themselves. I'm processing the form with PHP and storing the value of textarea in a Mysql DB. When I retrieve the value from the DB to output it again in the textarea so users can edit what they wrote I'm using htmlentities function to encode special html characters. The problem is that this function is adding 2 extra new lines to each \r\n that it founds. For example if my value in the DB is

Hello,

My name is ___.

I am a ______ .

When I use htmlentities to output it to the textarea what is being shown is this:

Hello,



My name is ____ .



I am a _______ .

When I print the value inside the textarea this is the function I'm using:

function profile_input_about( $profile_obj = false ) {
    $profile_about = ( $profile_obj ) ? htmlentities( $profile_obj->about, ENT_QUOTES | ENT_HTML5, 'UTF-8' ) : '';

    print $profile_about;
}

If I avoid using htmlentities or instead use htmlspecialchars this doesn't happen. Any clue why?

UPDATE

I made a stand-alone test:

<?php
    $text = "Hello there,\r\nThis is a test.\r\nWhat do you see?";
?>
<!DOCTYPE html>
<html>
<body>
    <textarea><?php print htmlentities( $text, ENT_QUOTES | ENT_HTML5, 'UTF-8' ) ?></textarea>
    <textarea><?php print htmlspecialchars( $text, ENT_QUOTES | ENT_HTML5, 'UTF-8' ) ?></textarea>
</body>
</html>

htmlentities() Definitely adds an extra \n.

The results are:

Hello there,

This is a test.

What do you see?

And

Hello there,
This is a test.
What do you see?

If I don't use the ENT_HTML5 flag, the problem disappears. It shows the text as it is.

Is this supposed to be this way or is this a php bug?

Was it helpful?

Solution

EDITED -

Per the docs, with htmlentities, "all characters which have HTML character entity equivalents are translated into these entities." Meaning, \r is interpreted as having an HTML character entity equivalent of \n, and thus you have two new lines.

With htmlspecialchars, only characters like quotes, </>, & are translated. The \r\n remains, leading to the expected result of just one new line marker between each line of text.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top