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:
Input:
This is a
test.
Output:
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?
2 Answers 2
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'
Comments
Just use double quotes on str_replace
str_replace('\r',"\r",str_replace('\n',"\n",$resolution));
http://php.net/manual/en/language.types.string.php
or if you're really dealing with double backslashes:
str_replace('\\\\r',"\r",str_replace('\\\\n',"\n",$resolution));
<textarea></textarea>between<pre>tags. If you store your data in a database you might want to put the insert between<pre>tags aswell