Counting number of occurances of a number in a string
I want to count the number of occu开发者_如何学编程rances of each number in a given string. For eg:-
'11 1 2 5 1 2 4 2 7 11 3002 221 3002'
This is a string with spaces between the numbers. I used str_wrd_cnt() and array_count_values() but str_word_cnt() considers only characters in the string.
Can anyone help me with the code?
You want to split the string into an array of numbers, then count the values. In PHP maybe you'd do something like array_count_values(explode(' ', '11 1 2 5 1 2 4 2 7 11 3002 221 3002'))
I can't understand you very well, but to get max count of these numbers, try this:
$string = '11 1 2 5 1 2 4 2 7 11 3002 221 3002';
$exp = explode(" ", $string);
$count = 0;
foreach($exp as $numbers) {
$count+=$numbers;
}
echo $count;
There:
function find($str, $number) {
$start = 0;
$count = 0;
while (true) {
$start = strpos($str, $number, $start);
if ($start === false)
break;
$count++;
$start++;
}
return $count;
}
echo find('11 14 11 12 11', '11');
精彩评论