【问题标题】:Remove white-spacing but keep paragraphs [duplicate]删除空白但保留段落[重复]
【发布时间】:2021-11-29 22:17:32
【问题描述】:

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

我有这个代码:

$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() 函数对我来说不是一个好的解决方案,因为我需要将此输出放在一个文本区域中。

【问题讨论】:

  • 您是在浏览器中还是在 CLI 中获得该输出?如果在浏览器中查看源代码或根据需要将输出放在<pre></pre> 或文本区域中。浏览器不会将\n 显示为页面上的换行符
  • 我在浏览器中获得了该输出,我想在带有换行符的浏览器中获得相同的输出。

标签: php regex preg-replace


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    $replaced = preg_replace('/\s\s+/', ' ', "1st.     line
    2nd.      line goes here
    
    3rd. line   goes   there");
    
    echo "<textarea>{$replaced}</textarea>";
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-27
      • 1970-01-01
      • 2016-09-18
      • 1970-01-01
      • 1970-01-01
      • 2022-12-05
      • 2021-10-01
      • 1970-01-01
      相关资源
      最近更新 更多