$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 ";

当前回答

可以使用preg_replace替换PCRE正则表达式: http://php.net/manual/en/function.preg-replace.php

$new_string = preg_replace("/\r\n|\r|\n/", ' ', $old_string);

将用空格替换新行或返回字符。如果你不想用任何东西替换它们,将第二个参数改为“。

其他回答

为了提高速度,应该使用str_replace,并对数组使用双引号

str_replace(array("\r\n","\r"),"",$string);

转义序列\R匹配通用换行符

也就是说,任何被Unicode视为换行序列的东西。这包括由\v(垂直空格)匹配的所有字符,以及多字符序列\x0D\x0A…

$string = preg_replace('/\R+/', " ", $string);

在8位非utf -8模式下\R相当于以下内容:(?>\ R \n|\n|\x0b|\f|\ R |\x85)…pcre.org

Regex101演示

这就是我要用的模式

$string = preg_replace('@[\s]{2,}@',' ',$string);

以下代码工作所有文本请使用它:

$des = str_replace('\n',' ',$des);
$des = str_replace('\r',' ',$des);

您可以删除新行和多个空白。

$pattern = '~[\r\n\s?]+~';
$name="test1 /
                     test1";
$name = preg_replace( $pattern, "$1 $2",$name);

echo $name;