【问题标题】:replace multiple spaces by non breaking spaces用不间断空格替换多个空格
【发布时间】:2017-03-29 09:17:42
【问题描述】:

当有多个空格时,如何用  替换除第一个(空白)之外的所有空格?

特别要求与php的preg_replace一起使用,所以PCRE。

"This is     my text."

应该转换成

"This is     my text."

【问题讨论】:

  • 试试preg_replace("!\s+!", " ", $text);。可以举个例子吗?
  • 也许,你想要preg_replace("!\s{2,}!", " ", $text);
  • @WiktorStribiżew 上面提供的示例。
  • 这是一个有趣的问题。我无法用\G 实现它。但我认为您可以只使用preg_replace('~(?<=\s)\s~', ' ', $s) - 请参阅this demo。

标签: php html regex pcre


【解决方案1】:

您似乎只需要用另一个空格符号替换前面的每个空格。使用基于后视的方法:

(?<=\s)\s

请参阅regex demo。

(?&lt;=\s) 是一个正向后视,它要求在当前位置之前立即存在一个空白,但该空白未被消耗,因此不会被替换。

下面是PHP demo:

$s = "This is     my text.";
echo preg_replace('~(?<=\s)\s~', '&nbsp;', $s);
// => This is &nbsp;&nbsp;&nbsp;&nbsp;my text.

【讨论】:

    【解决方案2】:

    不止一个空格是&gt;=2

    PHP code demo

    <?php
    
    echo preg_replace("!\s{2,}!", " &nbsp;", "Welcome to stack  overflow");
    

    输出:

    Welcome to stack &nbsp;overflow
    

    【讨论】:

    • 有可能OP不想要&amp;nbsp;前面的空格,替换应该是"&amp;nbsp;"(没有初始空格)。
    【解决方案3】:

    你需要做的是像这样使用Regex Lookahead &amp; Lookbehind:

    像这样:

    <?php
    echo preg_replace("/\s(?=\s+)|(?<=\s)\s/", "&nbsp;", "Welcome to stack       overflow");
    

    输出

    Welcome to stack&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;overflow
    

    在这里测试:https://regex101.com/r/DGraSS/1 - 提供了很好的解释:)

    【讨论】:

    • 这几乎是我所需要的,但我得到了一个额外的&amp;nbsp;(例如,当只有 4 个空格时为 5,当有 8 个空格时为 9)并且保留第一个空格会更好( "欢迎堆叠   ) 以允许之前休息
    • 我刚刚在php 7.x下再次测试,空格数等于输出nbsps的个数。
    猜你喜欢
    • 2011-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-25
    • 2010-11-19
    • 1970-01-01
    相关资源
    最近更新 更多