php 如何从字符串中转义新行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3200087/
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 escape new line from string
提问by user370527
is there any php method to remove new line char from string?
是否有任何 php 方法可以从字符串中删除换行符?
$str ="
Hi
there
";
my string contains a new line char between 'Hi' and 'there' i want output as a "Hi there".I don't want to use regular expression.
我的字符串在“嗨”和“那里”之间包含一个新行字符,我希望输出为“嗨,那里”。我不想使用正则表达式。
回答by alex
This is a bit confusing
这有点令人困惑
is there any php method to remove new line char from string?
是否有任何 php 方法可以从字符串中删除换行符?
It looks like you actually want them replaced with a space.
看起来您实际上希望将它们替换为空格。
$str = str_replace(array("\r\n", "\n", "\r"), ' ', $str);
Assuming the replacing goes from left to right, this should suit Windows text files.
假设替换从左到右,这应该适合 Windows 文本文件。
The first grouping is to match Windows newlines which use both \r and \n.
第一个分组是匹配同时使用 \r 和 \n 的 Windows 换行符。
回答by Dagg Nabbit
$str=str_replace("\n", "", $str);should do it.
$str=str_replace("\n", "", $str);应该这样做。
"\n"represents a newline in php.
"\n"表示 php 中的换行符。
回答by Mohsenme
There is no way to escape newline in PHP.
在 PHP 中没有办法转义换行符。
As mentioned in PHP documentation on stringsafter listing all escaped characters:
正如在列出所有转义字符后关于字符串的PHP 文档中所述:
As in single quoted strings, escaping any other character will result in the backslash being printed too.
与单引号字符串一样,转义任何其他字符也会导致打印反斜杠。
So you can do it by breaking your string in each line and concatenating them by dot like this:
所以你可以通过在每一行中打破你的字符串并用点连接它们来做到这一点,如下所示:
$str = "Hi " .
"there" .
"!";
回答by nathan
To get the expected results, you'll be needing:
要获得预期的结果,您将需要:
$str = trim(str_replace( array("\r\n","\r","\n",' '), ' ' , $str));
or with regex (which is fail safe, you can't account for all the additional spacing you may get with str_replace version):
或使用正则表达式(这是故障安全的,您无法考虑使用 str_replace 版本可能获得的所有额外间距):
$str = trim(preg_replace( array('/\v/','/\s\s+/'), ' ' , $str)); // 'Hi there'
回答by Yunus Malek
You can use below script.
您可以使用以下脚本。
$str=str_replace("\n", "", $str);
$str=str_replace("\n", "", $str);
Thanks
谢谢

