我想创建一个函数 countWords($str),它接受任何字符串并找到每个单词出现的次数。经验:
“你好世界”
字符 || 发生的次数
h 1
e 1
l 3
o 2
w 1
r 1
d 1
帮我 !!
谢谢....
尝试这个:
<?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
这是一种计算任何匹配项并返回数字的方法
<?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);
?>