确定PHP字符串中的重复字符

编程入门 行业动态 更新时间:2024-10-27 18:32:24
本文介绍了确定PHP字符串中的重复字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我发现了许多如何在字符串中查找重复字符的示例。我相信我的要求是独一无二的。

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字符串中的重复字符

本文发布于:2023-10-29 20:38:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1540687.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   字符   PHP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!