函数名称: 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
参数:
- $string (必需): 要计算单词数的字符串。
 - $format (可选): 指定返回值的格式。可选值为 0(默认)表示返回单词数,1 表示返回单词数组,2 表示返回位置数组。
 - $charlist (可选): 指定要从字符串中排除的字符列表。默认值为 null,表示不排除任何字符。
 
返回值:
- 当 $format 参数为 0 时,返回字符串中的单词数。
 - 当 $format 参数为 1 时,返回一个包含字符串中所有单词的数组。
 - 当 $format 参数为 2 时,返回一个包含字符串中所有单词的位置数组。
 
示例:
// 示例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
// )
注意事项:
- 默认情况下,str_word_count() 函数使用空格字符作为单词的分隔符,可以通过 $charlist 参数指定要排除的字符。
 - $charlist 参数中的字符将被视为单词分隔符,不会包含在返回的单词中。
 - 字符串中的标点符号和特殊字符会被视为单词的一部分。
 
 热门工具排行榜