我有一个这样的字符串: $ str ='汽车,狗,房子,狗,狗,房子,菜&#39 ;;
我怎样才能得到这样的输出:
dog #1 dog #2 dog #3 car house #1 house #2 dish
因为我想通过添加数字使重复的字符串成为唯一的字符串。
提前致谢!
答案 0 :(得分:2)
使用str_word_count
和array_count_values
函数的解决方案:
$str = 'car, dog, house, dog, dog, house, dish';
$counts = array_count_values(str_word_count($str, 1));
foreach ($counts as $name => $c) {
if ($c == 1) {
echo $name . PHP_EOL;
} else {
for ($i = 1; $i <= $c; $i++) echo $name . ' #'. $i . PHP_EOL;
}
}
输出:
car
dog #1
dog #2
dog #3
house #1
house #2
dish