$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 ";
当前回答
使用上述解决方案的组合,这条线对我来说很有效
$string = trim(str_replace('\n', '', (str_replace('\r', '', $string))));
它删除了“\r”和“\n”。
其他回答
文本中的换行符通常表示为:
\r\n -在Windows电脑上
\r -在苹果电脑上
\n - Linux
//Removes all 3 types of line breaks
$string = str_replace("\r", "", $string);
$string = str_replace("\n", "", $string);
什么:
$string = trim( str_replace( PHP_EOL, ' ', $string ) );
这应该是一个相当健壮的解决方案,因为\n不会在所有系统中正确工作,如果我没有错的话…
您可以尝试下面的代码将保留文本中的任何空白和新行。
$str = "
put returns between paragraphs
for linebreak add 2 spaces at end
";
echo preg_replace( "/\r|\n/", "", $str );
只需使用preg_replace()
$string = preg_replace('~[\r\n]+~', '', $string);
你可以在这个问题上使用str_replace(),尽管代码看起来不那么干净:
$string = str_replace(array("\n", "\r"), '', $string);
在脑海中看到它
我不确定这是否对已经提交的答案有任何价值,但我也可以张贴它。
// Create an array with the values you want to replace
$searches = array("\r", "\n", "\r\n");
// Replace the line breaks with a space
$string = str_replace($searches, " ", $string);
// Replace multiple spaces with one
$output = preg_replace('!\s+!', ' ', $string);