$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 = preg_replace('@[\s]{2,}@',' ',$string);

其他回答

这就是我要用的模式

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

你必须小心使用双换行符,这会导致双空格。使用这个非常有效的正则表达式:

$string = trim(preg_replace('/\s\s+/', ' ', $string));

多个空格和换行符被替换为单个空格。

编辑:正如其他人指出的那样,这个解决方案在单词之间匹配单个换行有问题。这在示例中没有出现,但是可以很容易地看到这种情况是如何发生的。另一种选择是这样做:

$string = trim(preg_replace('/\s+/', ' ', $string));

只需使用preg_replace()

$string = preg_replace('~[\r\n]+~', '', $string);

你可以在这个问题上使用str_replace(),尽管代码看起来不那么干净:

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

在脑海中看到它

您可以尝试下面的代码将保留文本中的任何空白和新行。

$str = "
put returns between paragraphs

for linebreak add 2 spaces at end

";

echo preg_replace( "/\r|\n/", "", $str );
$string = str_replace(array("\n", "\r"), ' ', $string);