【问题标题】:php replace multiple spaces with a single space [duplicate]php用一个空格替换多个空格[重复]
【发布时间】:2013-07-03 12:02:58
【问题描述】:

我想用多个空格替换字符串中的一个空格。请告知如何做。示例代码:

  <?php
    $input="bikash&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ranjan&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;nayak";
    echo $output =preg_replace('/(( )+|(\\n)+)/', '$2$3',$input);

    ?>

输出即将到来:
"bikash     ranjan          nayak"

【问题讨论】:

  • 你不是说要用单个空格替换多个空格吗?

标签: php


【解决方案1】:

你可以使用正则表达式

$output = preg_replace('!\s+!', ' ', $input);

【讨论】:

  • 它不起作用 rajeev 你可以检查一下,我也使用 preg_replace() 函数尝试了很多东西
  • 它在 OP 的 $input 内容中不起作用
  • 背后的原因   
  • 可以给出例如rajeev
  • 复制重复问题的答案无疑是一种收获代表的有趣方式,不是吗?如果是重复的,请将其标记为一个...
【解决方案2】:

试试这个。它将在浏览器上显示为单个空格

$output = str_replace("&nbsp", " ",$input);

【讨论】:

  • 好的,谢谢终于解决了我的替换字符串。在此之前我错过了一些东西,但我用过的同样的东西没有用。再次感谢
【解决方案3】:

试试这个

$output = implode("&nbsp;",array_filter(explode("&nbsp;",$input)));

【讨论】:

  • 不工作:我的代码根据
  • @BikashNayak:试试这个$output = implode("&amp;nbsp;",array_filter(explode("&amp;nbsp;",$input)));
【解决方案4】:
$output = preg_replace('!\(&nbsp;)+!', '&nbsp;', $input);

【讨论】:

    【解决方案5】:

    试试这个

    $output = preg_replace('/\s+/', ' ',$input);
    

    【讨论】:

      【解决方案6】:

      添加了解码 html 实体的额外行 ($input = html_ent.....)。

      $input="bikash&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ranjan&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;nayak";
      
      $input = html_entity_decode($input);
      
      echo $output =preg_replace('/(( )+|(\\n)+)/', '$2$3',$input);
      

      【讨论】:

        【解决方案7】:

        试试这个代码

        $input="bikash&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ranjan&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;nayak";
        $array = explode('&nbsp;', $input);
        $output = implode('&nbsp;', array_filter($array));
        echo $output;
        

        一个班轮:

        $output = implode('&nbsp;', array_filter(explode('&nbsp;', $input)));
        

        【讨论】:

        • 你是对的,但代码太长“工作良好”
        • 如果你愿意,我可以写成一行。您选择的解决方案不正确。它仍然会放下多个空格,但浏览器只会显示 1 或 2 个。而且这些空格不是“不间断空格”。
        猜你喜欢
        • 2013-11-25
        • 2011-01-05
        • 2012-06-04
        • 2010-11-19
        • 1970-01-01
        • 1970-01-01
        • 2011-10-22
        • 2013-05-30
        相关资源
        最近更新 更多