简体   繁体   English

将\\ r \\ n转换为文本区域中的换行符(不使用 <br> 标签)

[英]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. 我已经在整个网站和Google上进行了搜索,但找不到可行的解决方案。 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. 如果我输入的内容带有换行符,则在有回车符的地方将其解释为\\ r \\ n。 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: 现在,我发现通过使用如下所示的stripslashes来删除多余的斜杠很简单:

$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 我无法弄清楚如何将\\ r \\ n转换为换行符(即不使用
tag, since that would only output <br> within the textarea, where html would not be supported. 标记,因为这只会在textarea中输出<br>,而html不受支持。 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? 谁能对此有所启发?

Just use double quotes on str_replace 只需在str_replace上使用双引号

str_replace('\r',"\r",str_replace('\n',"\n",$resolution));

http://php.net/manual/en/language.types.string.php 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));

PHP has two different string building modes. PHP具有两种不同的字符串构建模式。 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' 现在, \\r\\n应该是输出中的活动回车符和换行符,而不是字符“ slash”,然后是'r'或'n'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM