This does not work with multibyte characters!
In the condition of posting could simply do:
$string = 'ddddeeeeeefffffffffgggggggggggggggggghhhhh';
$QntPorCaractere = count_chars($string, 1);
arsort($QntPorCaractere);
reset($QntPorCaractere);
echo strpos($string, key($QntPorCaractere));
Test this.
This will return the position of the first letter that is most repeating in the string. That is, if it is gabcdefggg would be 0, because the g is the most repeated and the first position of g is in 0.
The count_chars using the parameter 1 will return exactly the amount of occurrences (in value) and what was the character (in key) of the array, ie:
array(5) {
[100]=>
int(4)
[101]=>
int(6)
[102]=>
int(9)
[103]=>
int(18)
[104]=>
int(5)
}
In this case the 103 is the g, in the ASCII table, so that we can order, after all we want the one that has more occurrences, we use the arsort().
So we got the 103, which is contained in the array key using key($QntPorCaractere) and use it inside the strpos() that picks up the first occurrence.
It may seem wrong to use strpos($string, 103); instead of using something like strpos($string, pack('C', 103));. But the PHP manual says that "If Needle is not a string, it is converted to an integer and Applied as the ordinal value of a Character." then as it is in the format int o 103 passes to g internally by strpos.
What would happen if it were
abcaaaaaaaaaaaa? Would return0or would return3?– Inkeliz
I did what you asked in C#, I’m translating into php.
– Francisco