2 回答

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

TA貢獻1804條經驗 獲得超2個贊
您也可以使用數組函數并在一行中執行此操作,而無需使用foreach
.
echo implode(' ', array_keys(array_intersect(array_count_values(explode(' ', $string)),[1])));
- 2 回答
- 0 關注
- 105 瀏覽
添加回答
舉報