只删除单词之间的空白,但留下n



我使用PHP 7.4.1,并希望仅在两个单词之间删除双/三/n个空白。

我试着:

<?php
$str = "Hello World!
n
This is my  input  string.";
$str1 = preg_replace('/ss+/', ' ', $str);
echo $str1;
echo "n############################### n";
$str2 = preg_replace('/[s]+/mu', ' ', $str);
echo $str2;
echo "n############################### n";
这一方面删除了空白,但另一方面删除了两个n

.我希望有以下输出:

Hello World!

This is my input string.

有什么建议我做错了吗?

感谢您的回复!

使用文字边界:

$str = "Hello World!nThis is my  input  string.";
$output = preg_replace("/b[ ]{2,}b/", " ", $str);
echo $str . "n" . $output;

这个打印:

Hello World!
This is my  input  string.
Hello World!
This is my input string.

最新更新