$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”。

其他回答

这个选项也会删除制表符

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

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

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

echo $name;

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

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

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

用这个:

将换行符替换为空字符串:

$string = preg_replace("/[\\n\\r]+/", "", $string);

或者你可能想用一个空格替换换行符:

$string = preg_replace("/[\\n\\r]+/", " ", $string);

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

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

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

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

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