繁体   English   中英

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

[英]Replace all repeated occurrences of string for the single same

如何用相同的字符串替换所有重复出现的字符串:

我有这样的字符串:

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

我需要替换为:

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

我怎样才能做到这一点?

您可以这样做:

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

现场演示

或使用正则表达式:

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

分解:

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

现场演示

PHP代码:

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

您可以使用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;
?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM