用 PHP 替换 \r\n
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5449580/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Replacing \r\n with PHP
提问by njaknjak
I have a post form, which inserts my text in a MySQL database.
我有一个帖子表单,它将我的文本插入到 MySQL 数据库中。
I use
我用
$post_text = mysql_real_escape_string(htmlspecialchars($_POST['text']));
and want to replace the \r\n
which was automatically added.
并想替换\r\n
自动添加的。
I tried
我试过
$text = str_replace('\r\n','', $text);
$text = str_replace('\r\n','', $text);
$text = str_replace('\R\N','', $text);
$text = str_replace('\R\N','', $text);
$text = str_replace('/\r\n','', $text);
$text = str_replace('/r/n','', $text);
$text = str_replace('/\R\N','', $text);
$text = str_replace('/R/N','', $text);
but \r\n
is always included in my database entries.
但\r\n
始终包含在我的数据库条目中。
How can I fix this?
我怎样才能解决这个问题?
回答by Spudley
The main problem you have with all the variations you've tried is that both \n
and \r
are escape characters that are only escaped when you use them in a double-quoted string.
您尝试过的所有变体的主要问题是,\n
和\r
都是转义字符,只有在双引号 string 中使用它们时才会转义。
In PHP, there is a big difference between '\r\n'
and "\r\n"
. Note the single-quotes in the first, and double-quotes in the second.
在 PHP 中,'\r\n'
和"\r\n"
. 注意第一个中的单引号,第二个中的双引号。
So: '\r\n'
will result in a four character string containing a slash, an 'r', another slash and an 'n', whereas "\r\n"
will contain two characters, those being the new line and carriage return characters.
So: '\r\n'
将产生一个包含斜杠、'r'、另一个斜杠和一个 'n' 的四字符字符串,而"\r\n"
将包含两个字符,即换行符和回车符。
So the direct answer to your question is that you need to use the second of the examples you gave in the question, but with double quotes instead of single quotes:
所以你的问题的直接答案是你需要使用你在问题中给出的第二个例子,但用双引号而不是单引号:
$text = str_replace("\r\n",'', $text);
It's worth pointing out that this will remove allnew lines from the input, and replace them with nothing. If there is more than one new line in the input, they will all be removed. Without knowing more about your application, I don't know if this is what you want, but here are some thoughts:
值得指出的是,这将从输入中删除所有新行,并将它们替换为空。如果输入中有多个新行,它们将全部被删除。在不了解您的应用程序的情况下,我不知道这是否是您想要的,但这里有一些想法:
If you only want to remove blank lines (and other white space) from the endof the input string, you can use the
trim()
function instead.If you want to retain the formatting for output to HTML, then the
nl2br()
function will help you. If you want to output to HTML without the formatting, then you may not need to remove them, as the browser will not render line breaks from \n characters.If you replace new lines with nothing, as per your example, the last word of the first line will now run directly into the first word of the second line, and so on. You may prefer to replace them with a space character rather than nothing.
It is possible that users may submit the input with only
\n
without the matching\r
, or vice-versa (this may be due to their OS or browser, or a deliberate hack, or a number of other reasons). If you want to replace allinstances of both these characters, a more reliable way to do it would be to replace them individually, rather than relying on them being next to one-another.str_replace()
allows you to do this by specifying them in an array. You can also usestrtr()
orpreg_replace()
to achieve the same goal.
如果您只想从输入字符串的末尾删除空行(和其他空格),则可以改用该
trim()
函数。如果您想保留输出到 HTML 的格式,那么该
nl2br()
功能将为您提供帮助。如果您想在没有格式的情况下输出到 HTML,那么您可能不需要删除它们,因为浏览器不会从 \n 字符呈现换行符。如果您什么都不替换新行,根据您的示例,第一行的最后一个单词现在将直接运行到第二行的第一个单词中,依此类推。您可能更喜欢用空格字符代替它们而不是什么都不用。
用户可能会在
\n
没有匹配的情况下提交输入,\r
反之亦然(这可能是由于他们的操作系统或浏览器,或故意黑客攻击,或许多其他原因)。如果您想替换这两个字符的所有实例,更可靠的方法是单独替换它们,而不是依赖它们相邻。str_replace()
允许您通过在数组中指定它们来执行此操作。您也可以使用strtr()
或preg_replace()
来实现相同的目标。
Hope that helps.
希望有帮助。
回答by Itay Moav -Malimovka
try also
也试试
$text = str_ireplace(array("\r","\n",'\r','\n'),'', $text);
回答by Vineesh Kalarickal
if (!is_numeric($value)) {
$value = mysql_real_escape_string(trim($value));
$value = str_replace("\r\n",'', $value);
}
回答by fat_mike
I would suggest to use strtr() for multiple replacements when dealing with database entries. Also use double quotes as @Spudley suggested.
我建议在处理数据库条目时使用 strtr() 进行多次替换。也按照@Spudley 的建议使用双引号。
$text = strtr($text, array(
"\r\n" => "",
"\r" => "",
"\n" => "",
"\t" => " "));
strtr() -> Once a substring has been replaced, its new value will not be searched again.
strtr() -> 一旦子字符串被替换,它的新值将不会被再次搜索。
str_replace() -> If search is an array and replace is a string, then this replacement string is used for every value of search. The converse would not make sense, though.
str_replace() -> 如果 search 是一个数组,而 replace 是一个字符串,那么这个替换字符串用于搜索的每个值。但是,反过来说没有意义。
回答by Steve Hall
To preserve multiple line breaks I'm doing this:
为了保留多个换行符,我这样做:
$tempCONTENT = mysqli_real_escape_string($con, $_POST['promotion_content']);
$tempCONTENT = str_ireplace(array("\r\n","\r","\n",'\r','\n'),'<br />', $tempCONTENT);
$previewFORMATTED = str_ireplace(array('<br /><br />'),'<br />', $tempCONTENT);
echo $previewFORMATTED;
This is being used to process a text area form field. It preserves the number of line breaks the user inputs, changing them from \r\n to [br /]
这用于处理文本区域表单字段。它保留用户输入的换行次数,将它们从 \r\n 更改为 [br /]
I'm using this to display the input so the user can check it before I add it to the database. Using two submit buttons, one to check and another to submit, that doesn't do this. It just adds the data using mysqli_real_escape_string
我使用它来显示输入,以便用户可以在将其添加到数据库之前对其进行检查。使用两个提交按钮,一个用于检查,另一个用于提交,不会这样做。它只是使用 mysqli_real_escape_string 添加数据
I'm then using a str_ireplace to turn the correct number of [br /] back into \r\n so I can echo the result back into the text area to make it easy for them to edit.
然后我使用 str_ireplace 将正确数量的 [br /] 转回 \r\n 以便我可以将结果回显到文本区域中,以便于编辑。
So my final code looks like this:
所以我的最终代码如下所示:
$tempCONTENT = mysqli_real_escape_string($con, $_POST['promotion_content']);
$tempCONTENT = str_ireplace(array("\r\n","\r","\n",'\r','\n'),'<br />', $tempCONTENT);
$previewFORMATTED = str_ireplace(array('<br /><br />'),'<br />', $tempCONTENT);
echo $previewFORMATTED;
$formOUTPUT = str_ireplace(array('<br />'),"\r\n", $previewFORMATTED);
I've tested this on Safari and Chrome and it works fine. I've not tested IE, but nothing ever works on IE!
我已经在 Safari 和 Chrome 上对此进行了测试,效果很好。我没有测试过 IE,但在 IE 上没有任何效果!
But I did find another issue. If the user enters HTML like this:
但我确实发现了另一个问题。如果用户像这样输入 HTML:
<h1>heading</h1><p>some text</p>
it's fine, but if they do the following (which is more likely)
没关系,但如果他们执行以下操作(更有可能)
<h1>heading</h1>
<p>some text</p>
Then I get a huge space between the heading and the paragraph.
然后我在标题和段落之间有一个巨大的空间。
I tried to fix it with this code:
我试图用以下代码修复它:
$tempCONTENT = str_ireplace(array(">\r\n<",">\r<",">\n<",'>\r<','>\n<'),'><', $tempCONTENT);
but that didn't work :( I still get the huge gap as it's adding an extra [br /] between the h1 and p tags.
但这不起作用:(我仍然得到了巨大的差距,因为它在 h1 和 p 标签之间添加了一个额外的 [br /]。
For now I'm just going to tell them to not add a line break between html tags and the result should be good :)
现在我只是要告诉他们不要在 html 标签之间添加换行符,结果应该很好:)
I hope somebody found this useful.
我希望有人发现这很有用。
回答by Your Common Sense
For a MySQL database you shouldn't replace anything.
对于 MySQL 数据库,您不应替换任何内容。
- in case it's just literal
\r\n
in$post_text
- it's okay, it's proper format for the SQL query. - in case it's
\\r\\n
in$post_text
that becomes\r\n
in the database - you have escaped your string twiceand should not replace anything but rather get rid of excessive escaping
- 如果它只是文字
\r\n
输入$post_text
- 没关系,它是 SQL 查询的正确格式。 - 在情况下,它
\\r\\n
在$post_text
变成\r\n
数据库-你已经逃脱你的字符串两次,而不应取代任何东西,而是摆脱过度逃逸的
So, you have to make it look like \r\n
in in the $post_text
before insert, and you'll be able apply nl2br()
function on it before output.
所以,你必须让它看起来像\r\n
在$post_text
插入之前,你将能够nl2br()
在输出之前对其应用函数。