[英]Replace all repeated occurrences of string for the single same
How replace all repeated occurrences of string for the single same: 如何用相同的字符串替换所有重复出现的字符串:
I have string like: 我有这样的字符串:
1-string-2-string-3-string-55-otherstring-66-otherstring
I need replace for: 我需要替换为:
1-2-3-string-55-66-otherstring
How can I do that? 我怎样才能做到这一点?
You could do this: 您可以这样做:
$str = '1-string-2-string-3-string-55-otherstring-66-otherstring';
print_r(implode('-', array_reverse(array_unique(array_reverse(explode('-', $str))))));
Or using Regular Expressions: 或使用正则表达式:
(\w++)-?(?=.*\b\1\b)
Breakdown: 分解:
(\\w++)
Match and capture a word (\\w++)
匹配并捕获一个单词 -?
Match following hyphen if any 匹配以下连字符(如果有) (?=
Start of positive lookahead (?=
开始积极向前看
.*\\b\\1\\b
Recent captured word should repeat .*\\b\\1\\b
最近捕获的单词应重复 )
End of lookahead )
提前结束 PHP code: PHP代码:
echo preg_replace('~(\w++)-?(?=.*\b\1\b)~', '', $str);
You can use str_word_count to get words and array_count values to count how much time each word is meeting in string 您可以使用str_word_count获取单词,并使用array_count值计算每个单词在字符串中相遇的时间
and replace each word when the count is greater than 1 并在计数大于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.