### [PHP函数介绍:str_word_count()函数](https://www.prosaas.cn/article/11458) **Published:** 2023-11-04T02:00:50 **Author:** 5201314 **Excerpt:** PHP函数介绍:str_word_count()函数及代码示例一、概述在PHP中,str_word_count… ![20231212160653635](https://zhiqipro.oss-cn-beijing.aliyuncs.com/2023/11/20231212160653635.jpg "20231212160653635") PHP函数介绍:str\_word\_count()函数及代码示例 一、概述 在PHP中,str\_word\_count()函数用于统计字符串中的单词数量。本文将详细介绍该函数的用法,并给出相应的代码示例。 二、函数语法 str\_word\_count(string $string \[, int $format = 0 \[, string $charlist\]\]) 参数说明: - $string:必需,要统计单词数量的字符串。 - $format:可选,指定返回结果的格式,取值为0、1或2,默认为0。 - 如果$format为0,则函数返回字符串中的单词数量(默认)。 - 如果$format为1,则函数返回一个数组,其中包含字符串中的每个单词。 - 如果$format为2,则函数返回一个关联数组,其中键名为字符串中每个单词的位置,键值为对应的单词。 - $charlist:可选,指定在统计单词时忽略的字母列表。默认为空格、制表符和换行符等标点符号。 三、使用示例 下面给出一些具体的代码示例,帮助理解str\_word\_count()函数的使用方法。 示例1:统计字符串中的单词数量 $string = "Hello, how are you today?"; $wordCount = str\_word\_count($string); echo "单词数量:".$wordCount; 输出结果:单词数量:5 示例2:返回字符串中的每个单词 $string = "Hello, how are you today?"; $wordsArray = str\_word\_count($string, 1); echo "单词列表:"; foreach ($wordsArray as $word) { echo $word." "; } 输出结果:单词列表:Hello how are you today 示例3:返回字符串中每个单词的位置和对应的单词 $string = "Hello, how are you today?"; $wordsArray = str\_word\_count($string, 2); echo "单词列表:"; foreach ($wordsArray as $position => $word) { echo "位置".$position.":".$word." "; } 输出结果:单词列表:位置0:Hello 位置6:how 位置10:are 位置14:you 位置18:today 示例4:自定义忽略的字母列表 $string = "Hello, how are you today?"; $wordCount = str\_word\_count($string, 0, "o"); echo "单词数量:".$wordCount; 输出结果:单词数量:3 示例5:使用正则表达式匹配单词 $string = "Hello, how are you today?"; preg\_match\_all('/w+/', $string, $matches); echo "单词列表:"; foreach ($matches\[0\] as $word) { echo $word." "; } 输出结果:单词列表:Hello how are you today 四、总结 str\_word\_count()函数是PHP中一个简单实用的函数,用于统计字符串中的单词数量。通过设置不同的参数,我们可以获取到单词数量、单词列表以及每个单词的位置和对应的单词。同时,我们还可以自定义忽略的字母列表。这些功能使得str\_word\_count()函数在字符串处理中具有广泛的应用价值。希望本文的介绍能够帮助读者更好地理解和应用该函数。 以上就是PHP函数介绍:str\_word\_count()函数的详细内容,更多请关注知企PROSAAS其它相关文章! **Tags:** format, int, php, String, 关联数组, 字符串, 正则表达式 **Categories:** 后端开发 ---