Reputation: 51
i want create a function countWords($str) that takes any string of characters and finds the number of times each word occurs. exp:
"hello world"
character || number of times ouccr
h 1
e 1
l 3
o 2
w 1
r 1
d 1
help me !!
Thanks....
Upvotes: 2
Views: 2369
Reputation: 4370
Try this:
<?php
$str = 'hello world';
$str = str_replace(' ', '', $str);
$arr = str_split($str);
$rep = array_count_values($arr);
foreach ($rep as $key => $value) {
echo $key . " = " . $value . '<br>';
}
Output:
h = 1
e = 1
l = 3
o = 2
w = 1
r = 1
d = 1
Upvotes: 2
Reputation: 898
Here's one way counts any matches and returns the number
<?php
function counttimes($word,$string){
//look for the matching word ignoring the case.
preg_match_all("/$word/i", $string, $matches);
//count all inner array items - 1 to ignore the initial array index
return count($matches, COUNT_RECURSIVE) -1;
}
$string = 'Hello World, hello there Hello World';
$word = 'h';
//call the function
echo counttimes($word,$string);
?>
Upvotes: 0