substr_count有类似的功能吗?

时间:2015-01-05 09:47:59

标签: php

我使用substr_count函数来计算单词出现在字符串中的次数。例如,给出句子,

  

saya akan menyalakan mobil di depan garasi

我想在这句话中统计 akan menyalakan 这些词。

我使用了函数substr_count,但结果很奇怪。

我看到的结果是

"akan" = 2 word
"menyalakan" = 1 word

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

如果您想获取有关字符串中使用的字词的信息,可以使用str_word_count,之后您可以使用array_count_values计算相似字数。

如果要搜索所有不区分大小写的单词,请使用array_map处理数组($ array,' strtolower');

示例:

$all_words = str_word_count($str, 1);
$all_words = array_map($all_words, 'strtolower'); // optional
$count = array_count_values($all_words);

echo $count["akan"]; // 2;
echo $count["menyalakan"]; // 3;

答案 1 :(得分:0)

尝试使用str_word_count()

 function countWord($str,$key) { 
   return array_count_values(str_word_count($str, 1))[$key];
 } 
 $str = "saya akan menyalakan mobil di depan garasi";

 echo countWords( $str , 'akan' );          // Output 1
 echo countWords( $str , 'menyalakan' );    // Output 1