str_word_count()

1. 定义

该函数计算字符串中的单词数量。

2. 语法

str_word_count ( string $string [, int $format = 0 [, string $charlist ]] ) : mixed

3. 参数说明

参数 可选性 数据类型 描述
$string 必需 字符串 待统计的字符串
$format 可选 整型 指定函数的返回值
$charlist 可选 字符串 附加字符串列表,其中的字符将被视为单词的一部分

其中,$format的可选值有:

  • 0:返回单词的数量
  • 1:返回一个包含统计出的所有单词的数组
  • 2:返回关联数组,键名为对应单词在字符串中的索引位置

4. 示例

<?php

// str_word_count()
// 该函数统计一个字符串中单词的数量

$str = 'hello, PHP world! We will learn more knowledge about PHP!';

$res = str_word_count($str, 0);
var_dump($res);// 输出:int(10)

$res = str_word_count($str, 1);
var_dump($res);
/* 输出:
array(10) {
  [0]=>
  string(5) "hello"
  [1]=>
  string(3) "PHP"
  [2]=>
  string(5) "world"
  [3]=>
  string(2) "We"
  [4]=>
  string(4) "will"
  [5]=>
  string(5) "learn"
  [6]=>
  string(4) "more"
  [7]=>
  string(9) "knowledge"
  [8]=>
  string(5) "about"
  [9]=>
  string(3) "PHP"
}
*/

$res = str_word_count($str, 2);
var_dump($res);
/* 输出:
array(10) {
  [0]=>
  string(5) "hello"
  [7]=>
  string(3) "PHP"
  [11]=>
  string(5) "world"
  [18]=>
  string(2) "We"
  [21]=>
  string(4) "will"
  [26]=>
  string(5) "learn"
  [32]=>
  string(4) "more"
  [37]=>
  string(9) "knowledge"
  [47]=>
  string(5) "about"
  [53]=>
  string(3) "PHP"
}
*/

$str = 'hello, PHP world! We will learn more knowledge about PHP&coding!';
$res = str_word_count($str, 0);
var_dump($res);// 输出:int(11)
$res = str_word_count($str, 2, '&');// PHP&coding 被视为一个单词
var_dump($res);
/* 输出:
array(10) {
  [0]=>
  string(5) "hello"
  [7]=>
  string(3) "PHP"
  [11]=>
  string(5) "world"
  [18]=>
  string(2) "We"
  [21]=>
  string(4) "will"
  [26]=>
  string(5) "learn"
  [32]=>
  string(4) "more"
  [37]=>
  string(9) "knowledge"
  [47]=>
  string(5) "about"
  [53]=>
  string(10) "PHP&coding"
}
*/

5. 延展阅读

  • explode():使用一个字符串分割另一个字符串,返回被分割后子字符串组成的数组
  • count_chars():返回指定字符串中,每个字节值出现的次数数组
  • substr_count():返回指定子字符串在字符串中出现的次数