Home >Backend Development >PHP Tutorial >PHP function str_word_count() that counts the number of words in a string

PHP function str_word_count() that counts the number of words in a string

黄舟
黄舟Original
2017-11-03 14:11:291694browse

Example

Count the number of words in the string "Hello World!":

<?php
echo str_word_count("Hello world!");
?>

Definition and usage

str_word_count() function counts the number of words in the string .

Syntax

str_word_count(string,return,char)
Parameters Description
string Required. Specifies the string to check.
return Optional. Specifies the return value of the str_word_count() function.

Possible values:

  • 0 - Default. Returns the number of words found.

  • 1 - Returns an array containing the words in a string.

  • 2 - Returns an array in which the key is the position of the word in the string and the key value is the actual word.

char Optional. Specifies special characters that are recognized as words.

Technical details

Return value: Returns a number or an array, depending The selected return parameter.
PHP Version: 4.3.0+
Change Log: In PHP 5.1 , added char parameter.

更多实例

实例 1

返回包含字符串中的单词的数组:

<?php
print_r(str_word_count("Hello world!",1));
?>

实例 2

返回一个数组,其中的键名是单词在字符串中的位置,键值是实际的单词:

<?php
print_r(str_word_count("Hello world!",2));
?>

实例 3

没有 char 参数和有 char 参数:

<?php
print_r(str_word_count("Hello world & good morning!",1));
print_r(str_word_count("Hello world & good morning!",1,"&"));
?>


The above is the detailed content of PHP function str_word_count() that counts the number of words in a string. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn