PHP中重复的单词

时间:2019-01-11 08:06:43

标签: php

我可能有关于PHP是否可用于检测重复项的信息,以及关于不删除并将其添加到-1,-2,-3的书

示例:

$string = 'H4,H4,H3,WY21W,W5W,W5W,WY21W,W21/5W,W21/5W,W21W,W16W,W5W';

结果:

$output = 'H4,H4-1,H3,WY21W,W5W,W5W-1,WY21W-1,W21/5W,W21/5W-1,W21W,W16W,W5W-2'

2 个答案:

答案 0 :(得分:2)

$string = 'H4,H4,H3,WY21W,W5W,W5W,WY21W,W21/5W,W21/5W,W21W,W16W,W5W';
$parts = explode(',', $string); // split by comma
$used = []; // array to count the number of occurrences
$result = []; // array to take the "new" elements

foreach($parts as $part) {
  if(isset($used[$part])) { // if there is an entry in the counter array already,
                            // increment it by one,
    $used[$part]++;
  }
  else {                    // else initialize with 0
    $used[$part] = 0;
  }
  // put part into new array, append -(counter) if counter > 0
  $result[] = $part . ($used[$part] ? '-'.$used[$part] : '');
}

echo implode(',', $result); // join together with comma

答案 1 :(得分:1)

与misorude的答案几乎相同。

<?php

$string = 'H4,H4,H3,WY21W,W5W,W5W,WY21W,W21/5W,W21/5W,W21W,W16W,W5W';
$values  = explode(',', $string);

foreach($values as $k => $value)
    if($counts[$value] = !isset($counts[$value]) ? 0 : $counts[$value]-1)
        $values[$k] = $value . $counts[$value];

print implode(',', $values);

输出:

H4,H4-1,H3,WY21W,W5W,W5W-1,WY21W-1,W21/5W,W21/5W-1,W21W,W16W,W5W-2