MagicHat
MagicHat

Reputation: 429

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?

Upvotes: 0

Views: 36

Answers (2)

Davit Huroyan
Davit Huroyan

Reputation: 302

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

Upvotes: 0

revo
revo

Reputation: 48741

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

Upvotes: 1

Related Questions