我想创建一个函数countWords($ str),它接受任何字符串并查找每个单词出现的次数。 EXP:
“你好世界”
字符 || 次数ouccr
h 1
e 1
l 3
o 2
w 1
r 1
d 1
帮助我!!
...谢谢
答案 0 :(得分:2)
试试这个:
<?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>';
}
输出:
h = 1
e = 1
l = 3
o = 2
w = 1
r = 1
d = 1
答案 1 :(得分:0)
这是一种计算任何匹配的方法并返回数字
<?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);
?>