【问题标题】:Replace multiple dashes with one dash用一个破折号替换多个破折号
【发布时间】:2015-04-25 13:03:22
【问题描述】:

我有一个如下所示的字符串:

something-------another--thing
       //^^^^^^^       ^^

我想用一个破折号替换多个破折号。

所以预期的输出是:

something-another-thing
       //^       ^

我尝试使用str_replace(),但我必须为每个可能的破折号重新编写代码。那么如何用一个破折号替换任意数量的破折号呢?

对于里齐尔:

试过了:

 $mystring = "something-------another--thing";
 str_replace("--", "-", $mystring);
 str_replace("---", "-", $mystring);
 str_replace("----", "-", $mystring);
 str_replace("-----", "-", $mystring);
 str_replace("------", "-", $mystring);
 str_replace("-------", "-", $mystring);
 str_replace("--------", "-", $mystring);
 str_replace("---------", "-", $mystring);
 etc...

但字符串在两个单词之间可能有 10000 行。

【问题讨论】:

  • 你试过了吗?
  • @Rizier123 他说他试过str_replace
  • @Barmar 我知道,但我读了太多次,OP 从来没有用他们的尝试编辑过他们的问题。所以现在我想看代码,而不仅仅是读“我试过”

标签: php string str-replace


【解决方案1】:

使用preg_replace 替换模式。

$str = preg_replace('/-+/', '-', $str);

正则表达式 -+ 匹配任何包含 1 个或多个连字符的序列。

如果您不懂正则表达式,请阅读www.regular-expression.info 的教程。

【讨论】:

    【解决方案2】:

    你可以使用

    <?php
    $string="something-------another--thing";
    echo $str = preg_replace('/-{2,}/','-',$string);
    

    输出

    something-another-thing
    

    【讨论】:

      【解决方案3】:

      如果您有一个包含多个字符的字符串要清理,请使用:

      $string="Hello,,,my text contains unused characters... What can i do???"
      $newString=preg_replace('#([\-\.\?])\\1+#','$1',$string);
      

      如果您有一个带有未知多个符号的字符串要清除,请使用:

      $string="!!!!A string with ooooother unknoooooown multiple Signs!!!!"
      $newString=preg_replace('#([.])\\1+#','$1',$string);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-10-09
        • 2011-03-08
        • 2011-08-28
        • 1970-01-01
        • 2023-03-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多