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 @ com

Explanation:

说明:

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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值