dihakz dihakz - 1 year ago 89
HTML Question

Converting \r\n to line breaks in a textarea (not using a <br> tag) in PHP

I have searched throughout this site and google, and could not find a viable solution. There are solutions, but none seem to work for me.

I have a text area that serves as the input for a form, as well as the output (editable) when displaying the form to edit. So, I have a textarea like so:

echo '<textarea>'.$resolution.'</textarea>';

If I enter something with line breaks, it is interpreted as \r\n wherever there is a carriage return. Example:

This is a


This is a\\r\\n\\r\\ntest.

Now, I found it simple to remove the extra slash by using stripslashes as follows:

$resolution = stripslashes($resolution);

...but, now the output is:

This is a\r\n\r\ntest.

I cannot figure out how to convert \r\n to a line break (that is, without using a
tag, since that would only output <br> within the textarea, where html would not be supported. I've tried all of the following, but none of them worked:

//Effort 1
$resolution = trim($resolution);

//Effort 2
$resolution = nl2br($resolution);

//Effort 3
$resolution = htmlentities($resolution);

//Effort 4
$resolution = preg_replace("\\r\\n","<br>",$resolution);

I'm now at a complete loss. Can anyone shed some light on this?

Answer Source

PHP has two different string building modes. The first uses single quotes, and will do absolutely no variable or special character substitutions. That's what you're using.

The second is variable-embedding in double quoted strings, which should work:

$text = str_replace("\\", "\", $text);
echo "<textarea>$text</textarea>";

The \r and \n should now be active carriage return and newline characters in your output, not the character "slash" and then an 'r' or 'n'

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download