【发布时间】:2018-10-25 10:06:45
【问题描述】:
如何将所有重复出现的字符串替换为单个相同的字符串:
我有这样的字符串:
1-string-2-string-3-string-55-otherstring-66-otherstring
我需要替换:
1-2-3-string-55-66-otherstring
我该怎么做?
【问题讨论】:
如何将所有重复出现的字符串替换为单个相同的字符串:
我有这样的字符串:
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;
?>
【讨论】: