PHP | 计算字符串中的单词总数
Given a string and we have to count the total number of words in it.
給定一個(gè)字符串,我們必須計(jì)算其中的單詞總數(shù)。
str_word_count() function
str_word_count()函數(shù)
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.
要查找字符串中的單詞總數(shù) ,我們可以使用str_word_count()函數(shù)(這是PHP中的庫(kù)函數(shù)),它返回字符串中的單詞總數(shù)。
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是必需的參數(shù),這是我們必須在其中查找單詞總數(shù)的字符串。
return – it is an optional parameter used for specifying the return type – it can accept three values
return –它是用于指定返回類型的可選參數(shù)–它可以接受三個(gè)值
- 0 – Which is the default value, it specifies the return the number of words in the string.
- 0 –這是默認(rèn)值,它指定返回字符串中的單詞數(shù)。
- 1 – It specifies the return of the array with the words.
- 1 –它指定帶有單詞的數(shù)組的返回。
- 2 – It specifies the return of the array where key is the position and value is the actual word.
- 2 –它指定數(shù)組的返回值,其中key是位置,而value是實(shí)際單詞。
char – it is an optional parameter – it is used to specify a special character to consider as a word.
char –這是一個(gè)可選參數(shù)–用于指定要視為單詞的特殊字符。
PHP code to count the total number of words in a string
PHP代碼計(jì)算字符串中單詞的總數(shù)
<?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:
說(shuō)明:
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中,我們具有函數(shù)str_word_count()來(lái)計(jì)算字符串中的單詞數(shù)。 我們使用相同的方法獲取字符串( $ str )中的單詞數(shù),并將函數(shù)的輸出存儲(chǔ)在( $ response )中,然后使用echo打印結(jié)果。
翻譯自: https://www.includehelp.com/php/count-the-total-number-of-words-in-a-string.aspx
總結(jié)
以上是生活随笔為你收集整理的PHP | 计算字符串中的单词总数的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: oracle中dbms_如何在DBMS中
- 下一篇: c++ stl stack_C ++ S