我发现了许多如何在字符串中查找重复字符的示例。我相信我的要求是独一无二的。
I have found many examples of how to find repeat characters in a string. I believe my requirement is unique.
我有字符串
$string=aabbbccddd;我需要确定哪个字符重复最多。 因此,对于上面的示例,它会说重复最多的字符是 B。 但是,在上面的示例中,B和D都重复了3次。 需要发现这一点。 B和D都重复了3次。
I need to determine which character was repeated the most. So for the above example it would say The character repeated the most is "B". However in the example above both B and D are repeated 3 times. Would need to spot that. B AND D are both repeated 3 times.
这是我到目前为止的内容。从我需要的但从起点开始的FAR
This is what I have so far. FAR from what I need but starting point
<?php $string = "aabbbccddd"; $array=array($array); foreach (count_chars($string, 1) as $i => $val) { $count=chr($i); $array[]= $val.",".$count; } print_r($array); ?>有人能帮助我吗?
推荐答案基于georg的观点,我将使用正则表达式。这将使用数组键 dd => 2 和 ddd =处理拆分的重复项,例如 ddaaddd > 3 ,但在给定 ddaadd 时,只会显示 dd 的一项。要表示两者,则需要一个更复杂的数组:
Based on georg's great point, I would use a regex. This will handle split duplicates like ddaaddd with array keys dd=>2 and ddd=>3 but will only show one entry for dd when given ddaadd. To represent both would require a more complex array:
$string = "ddaabbbccddda"; preg_match_all('/(.)\1+/', $string, $matches); $result = array_combine($matches[0], array_map('strlen', $matches[0])); arsort($result);如果您只需要计算所有出现次数,请尝试:
If you only need a count of ALL occurrences try:
$result = array_count_values(str_split($string)); arsort($result);旧版答案:
如果您不这样做'没有重复的副本:
Legacy Answers:
If you don't have split duplicates:
$string = 'aabbbccddd'; $letters = str_split($string); $result = array_fill_keys($letters, 1); $previous = ''; foreach($letters as $letter) { if($letter == $previous) { $result[$letter]++; } $previous = $letter; } arsort($result); print_r($result);或者使用正则表达式:
preg_match_all('/(.)\1+/', $string, $matches); $result = array_combine($matches[1], array_map('strlen', $matches[0])); arsort($result);更多推荐
确定PHP字符串中的重复字符
发布评论