删除空白但保留段落

Remove white-spacing but keep paragraphs

我正在尝试编写删除所有空格但保留段落的代码。

我有这个代码:

$replaced = preg_replace('/\s\s+/', ' ', "1st.     line
2nd.      line goes here

3rd. line   goes   there");

echo $replaced;

作为输出我得到:

1st. line 2nd. line goes here 3rd. line goes there

但应该是这样的:

1st. line 
2nd. line goes here 

3rd. line goes there

nl2br() 函数对我来说不是一个好的解决方案,因为我需要将此输出放在文本区域中。

浏览器不会将 \n 显示为页面上的换行符。查看页面的源代码以确保输出符合要求,或者将输出放在 <pre></pre><textarea></textarea>:

$replaced = preg_replace('/\s\s+/', ' ', "1st.     line
2nd.      line goes here

3rd. line   goes   there");

echo "<textarea>{$replaced}</textarea>";

/[\t' ']+/ 这将删除制表符和空格