【问题标题】:Replace all repeated occurrences of string for the single same将所有重复出现的字符串替换为单个相同的字符串
【发布时间】:2018-10-25 10:06:45
【问题描述】:

如何将所有重复出现的字符串替换为单个相同的字符串:

我有这样的字符串:

1-string-2-string-3-string-55-otherstring-66-otherstring

我需要替换:

1-2-3-string-55-66-otherstring

我该怎么做?

【问题讨论】:

    标签: php regex replace


    【解决方案1】:

    你可以这样做:

    $str = '1-string-2-string-3-string-55-otherstring-66-otherstring';
    print_r(implode('-', array_reverse(array_unique(array_reverse(explode('-', $str))))));
    

    Live demo

    或者使用正则表达式:

    (\w++)-?(?=.*\b\1\b)
    

    细分:

    • (\w++)匹配并捕获一个单词
    • -? 匹配以下连字符(如果有)
    • (?= 正向前瞻开始
      • .*\b\1\b最近捕获的单词应该重复
    • )前瞻结束

    Live demo

    PHP 代码:

    echo preg_replace('~(\w++)-?(?=.*\b\1\b)~', '', $str);
    

    【讨论】:

    • 请注意,伙计,完美。
    【解决方案2】:

    您可以使用 str_word_count 获取单词和 array_count 值来计算每个单词在字符串中遇到的时间

    当计数大于1时替换每个单词

    <?php
    $text = "1-string-2-string-3-string-55-otherstring-66-otherstring";
    
    $words = str_word_count($text, 1); 
    
    $frequency = array_count_values($words);
    
    foreach($frequency as $item=>$count) {
    $item = rtrim($item,"-");
    
        if($count >1){
            $text = str_replace($item,"",$text);
        }
    }
    echo $text;
    ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-31
      • 1970-01-01
      • 2012-08-01
      • 2012-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-23
      相关资源
      最近更新 更多