簡體   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