亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

比較重復的單詞并將它們從 php 中的字符串中刪除

比較重復的單詞并將它們從 php 中的字符串中刪除

PHP
互換的青春 2022-10-28 15:01:19
一個字符串如下所示: $string = 'Super this is a test this is a test';輸出應該是:Super我正在嘗試從字符串中完全刪除重復的單詞。我發現的是: echo implode(' ',array_unique(explode(' ', $string)));但這是輸出: Super this is a test感謝您提供一個簡單的方法來做到這一點。
查看完整描述

2 回答

?
慕絲7291255

TA貢獻1859條經驗 獲得超6個贊

這是因為array_unique()將重復項減少到一個值:

接受一個輸入數組并返回一個沒有重復值的新數組。
源代碼

您需要先循環數組(盡管可以想象很多有創意的 array_filter/array_walk 東西):

$string = 'Super this is a test this is a test';


# first explode it

$arr = explode(' ', $string);


# get value count as var

$vals = array_count_values($arr);


foreach ($arr as $key => $word)

{

    # if count of word > 1, remove it

    if ($vals[$word] > 1) {

        unset($arr[$key]);

    }

}


# glue whats left together

echo implode(' ', $arr);

小提琴

作為一般項目使用的功能:

function rm_str_dupes(string $string, string $explodeDelimiter = '', string $implodeDelimiter = '')

{

    $arr = explode($explodeDelimiter, $string);

    $wordCount = array_count_values($arr);


    foreach ($arr as $key => $word)

    {

        if ($wordCount[$word] > 1) {

            unset($arr[$key]);

        }

    }


    return implode($implodeDelimiter, $arr);

}


# example usage

echo rm_str_dupes('Super this is a test this is a test');


查看完整回答
反對 回復 2022-10-28
?
慕婉清6462132

TA貢獻1804條經驗 獲得超2個贊

您也可以使用數組函數并在一行中執行此操作,而無需使用foreach.

echo implode(' ', array_keys(array_intersect(array_count_values(explode(' ', $string)),[1])));



查看完整回答
反對 回復 2022-10-28
  • 2 回答
  • 0 關注
  • 105 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號