【问题标题】:Remove duplicates of certain characters from string从字符串中删除某些字符的重复项
【发布时间】:2012-02-20 00:58:53
【问题描述】:

我如何才能从字符串$b 中删除数组$a 中找到的重复字符,前提是它们彼此相邻?

$a = array("a","b","c");
$b = "aabcccdef";

输出应该是

abcdef

可以使用正则表达式找到字符,但我不知道如何检测字符是否彼此相邻。

【问题讨论】:

    标签: php


    【解决方案1】:
    preg_replace( array('/a+/','/b+/','/c+/'),array('a','b','c',), $b );
    

    另一种更精细的方法可能是:

    preg_replace_callback('/(\w+)/', function ($matches) use ($a) {
    
       if ( in_array($matches[1][0],$a) )  //> if you need UTF-8 working use mb_substr here
        return $matches[1][0];
    
    },$b);
    
    //> both untested
    

    另一种方式,旧方式(在几个字符字符串上可能会更快一些):

    $c = '';
    $cache = false;
    for ($i=0;$i<strlen($b);$i++) {
      $char = $b[$i];
    
      if ($char !== $cache || !in_array($char,$a)) 
       $c .= $char;
    
      $cache=$char;
    }
    echo $c;
    

    【讨论】:

    • 太棒了,虽然我不得不承认我对第一个数组有点困惑。
    • 要创建第一个数组,您可以执行 foreach 并将 / +/ 添加到每个值,或者只使用第二个选项
    【解决方案2】:

    另一种方式:

    $expression = join('|', $a);
    $b = preg_replace('/(' . $expression . ')\1+/', '$1', $b);
    

    DEMO

    解释:

    生成的表达式将类似于(a|b)\1+,其中a|b 匹配a 或b。 \1 匹配第一个捕获组 (a|b) 匹配的任何内容。这就是匹配一组重复字符的方法。然后匹配被捕获组的内容 ($1) 替换。

    这不仅适用于单个字符,也适用于任何子字符串。

    如果字符串可以包含特殊的正则表达式字符,您应该先escape those characters(array_map('preg_quote', $a) 应该可以正常工作)。

    【讨论】:

      【解决方案3】:
      <?php
      $a = array('a', 'b', 'c');
      $b = 'aabcccdef';
      $c = '';
      for($i = 0; $i < strlen($b); $i++) {
          if(in_array($b[$i], $a) && (substr($c, -1) === $b[$i])) {
              continue;
          }
          $c .= $b[$i];
      }
      echo $c;
      

      【讨论】:

        猜你喜欢
        • 2013-01-05
        • 2016-03-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-21
        • 2013-02-16
        • 2018-11-03
        相关资源
        最近更新 更多