PHP | 计算字符串中的单词总数
Given a string and we have to count the total number of words in it.
给定一个字符串,我们必须计算其中的单词总数。
str_word_count() function
str_word_count()函数
To find the total number of words in a string, we can use str_word_count() function – which is a library function in PHP – it returns the total number of words in the string.
要查找字符串中的单词总数 ,我们可以使用str_word_count()函数(这是PHP中的库函数),它返回字符串中的单词总数。
Syntax:
句法:
str_word_count(string,return,char);Here,
这里,
string is a required parameter, this is the string in which we have to find the total number of words.
string是必需的参数,这是我们必须在其中查找单词总数的字符串。
return – it is an optional parameter used for specifying the return type – it can accept three values
return –它是用于指定返回类型的可选参数–它可以接受三个值
- 0 – Which is the default value, it specifies the return the number of words in the string.
- 0 –这是默认值,它指定返回字符串中的单词数。
- 1 – It specifies the return of the array with the words.
- 1 –它指定带有单词的数组的返回。
- 2 – It specifies the return of the array where key is the position and value is the actual word.
- 2 –它指定数组的返回值,其中key是位置,而value是实际单词。
char – it is an optional parameter – it is used to specify a special character to consider as a word.
char –这是一个可选参数–用于指定要视为单词的特殊字符。
PHP code to count the total number of words in a string
PHP代码计算字符串中单词的总数
<?php //input string $str = "The Quick brown fox jumps right over The Lazy Dog"; //counting the words by calling str_word_count function $response = str_word_count($str); //printing the result echo "There are ".$response." Words in <b>".$str."</b>".'<br/>';//input string $str = "Hello @ 123 . com"; //counting the words by calling str_word_count function $response = str_word_count($str); //printing the result echo "There are ".$response." Words in <b>".$str."</b>".'<br/>';//input string $str = "Hello @ IncludeHelp @ com"; //counting the words by calling str_word_count function //specify the '@' as a word $response = str_word_count($str, 0, '@'); //printing the result echo "There are ".$response." Words in <b>".$str."</b>".'<br/>'; ?>Output
输出量
There are 10 Words in The Quick brown fox jumps right over The Lazy Dog There are 2 Words in Hello @ 123 . com There are 5 Words in Hello @ IncludeHelp @ comExplanation:
说明:
In PHP, We have the function str_word_count() to count the number of words in a string. We use the same to get the number of words in the string ($str) and store the output of the function in ($response) then use echo to print the result.
在PHP中,我们具有函数str_word_count()来计算字符串中的单词数。 我们使用相同的方法获取字符串( $ str )中的单词数,并将函数的输出存储在( $ response )中,然后使用echo打印结果。
翻译自: https://www.includehelp.com/php/count-the-total-number-of-words-in-a-string.aspx
总结
以上是生活随笔为你收集整理的PHP | 计算字符串中的单词总数的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: oracle中dbms_如何在DBMS中
- 下一篇: 有关PHP、HTML单引号、双引号转义以