查找每个单词出现的次数并保存在php数组中


Finds the number of times each word occurs and save in php array

我想要创建一个函数countWords($str),它接受任何字符串并查找每个单词出现的次数。exp:

"你好世界"

字符|ouccr次数

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);
?>