php 如何替换回车
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3135919/
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
How to replace carriage return
提问by Asim Zaidi
I have a variable ($myClass[0]->comment;) that has carriage return in it. I want to replace all the carriage return in that variable with "\n"
how can I do that.
below may help a bit
我有一个$myClass[0]->comment;带有回车符的变量 ( )。我想用“ \n”替换该变量中的所有回车符,我该怎么做。
下面可能会有所帮助
$myClass[0]->comment;
Here is some output
这是一些输出
<?php
$test = explode(chr(13),$myClass[0]->comment );
var_dump($test);
?>
OUTPUT
输出
array
0 => string '12' (length=2)
1 => string '
' (length=1)
2 => string '
22' (length=3)
All I want is \ninstead of carriage return.
我想要的只是\n而不是回车。
回答by Paul Dixon
If you want to replace each CR (\r) with LF (\n), do this
如果要将每个 CR (\r) 替换为 LF (\n),请执行以下操作
$str=str_replace("\r", "\n", $str);
If you want a literal \n, do this
如果你想要一个文字 \n,这样做
$str=str_replace("\r", "\n", $str);
It's more likely you want to replace CR LF, in which simply search for "\r\n"instead.
您更有可能想要替换 CR LF,只需在其中搜索即可"\r\n"。
回答by Artefacto
preg_replace('/\r\n?/', "\n", $str);
This converts both Windows and Mac line endings to Unix line endings.
这会将 Windows 和 Mac 行尾转换为 Unix 行尾。
回答by Daniel Egeberg
You can use str_replace()to do this:
您可以使用以下str_replace()方法执行此操作:
$test = str_replace("\r", "\n", $myClass[0]->comment);
回答by Zak
you can use str_replace
你可以使用 str_replace
str_replace("\r", "\n", $text);
if you first wan't to clear out compound \r\n, so you don't get \n\n you could do
如果你首先不想清除复合 \r\n,所以你不会得到 \n\n 你可以做
str_replace("\r\n", "\n", $text);
str_replace("\r", "\n", $text);
回答by Ignacio Vazquez-Abrams
No you don't. You want this:
不,你没有。你要这个:
str_replace("\r\n", "\n", $myClass[0]->comment)
回答by tfont
Something a bit more functional (easy to use anywhere):
功能更强大的东西(易于在任何地方使用):
function replace_carriage_return($replace, $string)
{
return str_replace(array("\n\r", "\n", "\r"), $replace, $string);
}

