简体   繁体   中英

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))))));

Live demo

Or using Regular Expressions:

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

Breakdown:

  • (\\w++) Match and capture a word
  • -? Match following hyphen if any
  • (?= Start of positive lookahead
    • .*\\b\\1\\b Recent captured word should repeat
  • ) End of lookahead

Live demo

PHP code:

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

and replace each word when the count is greater than 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;
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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