$string = "
put returns between paragraphs
for linebreak add 2 spaces at end
";
想从字符串中删除所有新行。
我有这个正则表达式,它可以捕获所有的,问题是我不知道该用哪个函数来使用它。
/\r\n|\r|\n/
$string应该变成:
$string = "put returns between paragraphs for linebreak add 2 spaces at end ";
$string = "
put returns between paragraphs
for linebreak add 2 spaces at end
";
想从字符串中删除所有新行。
我有这个正则表达式,它可以捕获所有的,问题是我不知道该用哪个函数来使用它。
/\r\n|\r|\n/
$string应该变成:
$string = "put returns between paragraphs for linebreak add 2 spaces at end ";
当前回答
您可以尝试下面的代码将保留文本中的任何空白和新行。
$str = "
put returns between paragraphs
for linebreak add 2 spaces at end
";
echo preg_replace( "/\r|\n/", "", $str );
其他回答
使用上述解决方案的组合,这条线对我来说很有效
$string = trim(str_replace('\n', '', (str_replace('\r', '', $string))));
它删除了“\r”和“\n”。
对已接受答案的一些评论:
+表示“1或更多”。我认为你没有必要重复。我认为你可以简单地写“/\s+/”。
此外,如果想要删除字符串中的第一个和最后一个空白,则添加trim。
经过这些修改,代码将是:
$string = preg_replace('/\s+/', ' ', trim($string));
非常简单的
$hello = "
A
B
C
";
str_replace("
", " ", $hello);
// A B C
为了提高速度,应该使用str_replace,并对数组使用双引号
str_replace(array("\r\n","\r"),"",$string);
$string = str_replace(array("\n", "\r"), ' ', $string);