English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Manuale di base PHP

Manuale avanzato PHP

PHP & MySQL

Manuale di riferimento PHP

Uso e esempio della funzione PHP str_word_count()

    PHP String 字符串函数手册

    La funzione str_word_count() viene utilizzata per calcolare il numero di parole in una stringa.

Sintassi

mixed str_word_count ( string $string[, int $format = 0[, string $charlist]] )

Definizione e uso

Contare il numero di parole nella stringa. Se il parametro opzionale format non è specificato, il valore di ritorno è un numero intero che rappresenta il numero di parole. Se viene specificato il parametro format, il valore di ritorno sarà un array, il contenuto del quale dipende dal parametro format. Ecco elencati i valori possibili di format e i risultati corrispondenti.
对于这个函数的目的来说,单词的定义是一个与区域设置相关的字符串。这个字符串可以包含字母字符,也可以包含 "'" 和 "-" 字符(但不能以这两个字符开始)。

PHP 5.1.0 版本 新增 charlist 参数。

返回值

 返回一个数组或整型数,这取决于 format 参数的选择。

参数

序号参数与说明
1

string

必需。指定要检查的字符串。

2

format

可选。指定 str_word_count() 函数的返回值。

可能的值:

  • 0 - 默认。返回找到的单词的数目。

  • 1 - 返回包含字符串中的单词的数组。

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

3

charlist

可选。附加的字符串列表,其中的字符将被视为单词的一部分。

在线示例

试试下面的实例,返回包含字符串中的单词的数组,计算字符串中单词的数量:

<?php
   //计算字符串中单词的数量。
   echo str_word_count("w3codebox simply easy learning");
   //返回包含字符串中单词的数组
   print_r(str_word_count("Can i help you!",1));
   //没有 charlist 参数
   print_r(str_word_count("Can i help you & what's your name!",1));
   //有 charlist 参数
   print_r(str_word_count("Can i help you & what's your name!",1,'&'));
?>
测试看看‹/›

输出结果

4
Array
(
    [0] => Can
    [1] => i
    [2] => help
    [3] => you
)
Array
(
    [0] => Can
    [1] => i
    [2] => help
    [3] => you
    [4] => what's
    [5] => your
    [6] => name
)
Array
(
    [0] => Can
    [1] => i
    [2] => help
    [3] => you
    [4] => &
    [5] => what's
    [6] => your
    [7] => name
)

PHP String 字符串函数手册