函数名称: str_word_count()
适用版本: PHP 4, PHP 5, PHP 7
函数描述: str_word_count() 函数计算字符串中的单词数。
用法: str_word_count(string $string, int $format = 0, string|null $charlist = null): mixed
参数:
返回值:
示例:
// 示例1: 返回字符串中的单词数
$string = "Hello world! This is a sample string.";
$wordCount = str_word_count($string);
echo $wordCount; // 输出: 7
// 示例2: 返回一个包含字符串中所有单词的数组
$string = "Hello world! This is a sample string.";
$wordArray = str_word_count($string, 1);
print_r($wordArray);
// 输出:
// Array
// (
// [0] => Hello
// [1] => world
// [2] => This
// [3] => is
// [4] => a
// [5] => sample
// [6] => string
// )
// 示例3: 返回一个包含字符串中所有单词的位置数组
$string = "Hello world! This is a sample string.";
$positionArray = str_word_count($string, 2);
print_r($positionArray);
// 输出:
// Array
// (
// [0] => 0
// [6] => 6
// [12] => 12
// [16] => 16
// [19] => 19
// [21] => 21
// [28] => 28
// )
注意事项: