【问题标题】:Finds the number of times each word occurs and save in php array查找每个单词出现的次数并保存在 php 数组中
【发布时间】:2013-09-04 15:17:38
【问题描述】:

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

“你好世界”

字符 || 发生的次数

h                   1
e                   1
l                   3
o                   2
w                   1
r                   1
d                   1

帮帮我!!

谢谢....

【问题讨论】:

标签: php arrays string


【解决方案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

【讨论】:

    【解决方案2】:

    这是一种计算任何匹配项并返回数字的方法

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-04
      • 1970-01-01
      相关资源
      最近更新 更多