Php str count words

PHP str_word_count() Function

Count the number of words found in the string «Hello World!»:

Definition and Usage

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

Syntax

Parameter Values

Parameter Description
string Required. Specifies the string to check
return Optional. Specifies the return value of the str_word_count() function.
  • 0 — Default. Returns the number of words found
  • 1 — Returns an array with the words from the string
  • 2 — Returns an array where the key is the position of the word in the string, and value is the actual word

Technical Details

Return Value: Returns a number or an array, depending on the chosen return parameter
PHP Version: 4.3.0+
Changelog: The char parameter was added in PHP 5.1

More Examples

Example

Return an array with the words from the string:

Example

Return an array where the key is the position of the word in the string, and value is the actual word:

Example

Without and with the char parameter:

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

str_word_count

Подсчитывает количество слов, входящих в строку string . Если необязательный аргумент format не передан, возвращается целое число, равное количеству слов. В случае, если указан аргумент format , возвращается массив, содержимое которого зависит от значения format . Ниже описаны допустимые значения аргумента format и соответствующие им возвращаемые значения.

Для этой функции «слово» обозначает строку с алфавитными символами, зависящую от локали, которая также может содержать символы «‘» и «-«, но не может начинаться с них.

Список параметров

  • 0 — возвращает количество найденных слов
  • 1 — возвращается массив, содержащий все слова, входящие в строку string
  • 2 — возвращается массив, индексами которого являются позиции в строке string , а значениями — соответствующие слова.

Список дополнительных символов, которые будут рассматриваться как «слово»

Возвращаемые значения

Возвращает массив или целое число, в зависимости от указанного параметра format .

Список изменений

Версия Описание
5.1.0 Добавлен параметр charlist

Примеры

Пример #1 Пример использования str_word_count()

$str = «Hello fri3nd, you’re
looking good today!» ;

print_r ( str_word_count ( $str , 1 ));
print_r ( str_word_count ( $str , 2 ));
print_r ( str_word_count ( $str , 1 , ‘àáãç3’ ));

Результат выполнения данного примера:

Array ( [0] => Hello [1] => fri [2] => nd [3] => you're [4] => looking [5] => good [6] => today ) Array ( [0] => Hello [6] => fri [10] => nd [14] => you're [29] => looking [46] => good [51] => today ) Array ( [0] => Hello [1] => fri3nd [2] => you're [3] => looking [4] => good [5] => today ) 7

Смотрите также

  • explode() — Разбивает строку с помощью разделителя
  • preg_split() — Разбивает строку по регулярному выражению
  • split() — Разбиение строки на массив по регулярному выражению
  • count_chars() — Возвращает информацию о символах, входящих в строку
  • substr_count() — Возвращает число вхождений подстроки

Источник

str_word_count

Counts the number of words inside string . If the optional format is not specified, then the return value will be an integer representing the number of words found. In the event the format is specified, the return value will be an array, content of which is dependent on the format . The possible value for the format and the resultant outputs are listed below.

For the purpose of this function, ‘word’ is defined as a locale dependent string containing alphabetic characters, which also may contain, but not start with «‘» and «-» characters. Note that multibyte locales are not supported.

Parameters

Specify the return value of this function. The current supported values are:

  • 0 — returns the number of words found
  • 1 — returns an array containing all the words found inside the string
  • 2 — returns an associative array, where the key is the numeric position of the word inside the string and the value is the actual word itself

A list of additional characters which will be considered as ‘word’

Return Values

Returns an array or an integer, depending on the format chosen.

Changelog

Examples

Example #1 A str_word_count() example

$str = «Hello fri3nd, you’re
looking good today!» ;

print_r ( str_word_count ( $str , 1 ));
print_r ( str_word_count ( $str , 2 ));
print_r ( str_word_count ( $str , 1 , ‘àáãç3’ ));

The above example will output:

Array ( [0] => Hello [1] => fri [2] => nd [3] => you're [4] => looking [5] => good [6] => today ) Array ( [0] => Hello [6] => fri [10] => nd [14] => you're [29] => looking [46] => good [51] => today ) Array ( [0] => Hello [1] => fri3nd [2] => you're [3] => looking [4] => good [5] => today ) 7

See Also

  • explode() — Split a string by a string
  • preg_split() — Split string by a regular expression
  • count_chars() — Return information about characters used in a string
  • substr_count() — Count the number of substring occurrences

Источник

PHP: str_word_count() function

The str_word_count() function is used to count the number of words in a string.

str_word_count(string_name, nformat, add_chars)
Name Description Required /
Optional
Type
string_name The input string. Required String
nformat Specifies the return value of the str_word_count() function.
Supported values :
0 — returns the number of words found.
1 — returns an array contains all the words found within the specified string.
2 — returns an associative array, where the key is the numeric position of the word inside the string and the value is the actual word itself.
Optional Integer
add_chars A list of additional characters which will be considered as ‘word’. Optional String

Return value:

An array or an integer, depending on the format chosen.

Value Type: Mixed.

*Mixed: Mixed indicates that a parameter may accept multiple (but not necessarily all) types.

Pictorial Presentation

php-string-str_word_count()

'; print_r(str_word_count($string_name,1)); echo '
'; print_r(str_word_count($string_name,2)); ?>
5 
Array ( [0] => Welcome [1] => to [2] => w [3] => resource [4] => com )
Array ( [0] => Welcome [8] => to [11] => w [13] => resource [22] => com )

Previous: str_split
Next: strcasecmp

Follow us on Facebook and Twitter for latest update.

PHP: Tips of the Day

What is the difference between public, private, and protected?

  • public scope to make that property/method available from anywhere, other classes and instances of the object.
  • private scope when you want your property/method to be visible in its own class only.
  • protected scope when you want to make your property/method visible in all classes that extend current class including the parent class.
  • Weekly Trends
  • Java Basic Programming Exercises
  • SQL Subqueries
  • Adventureworks Database Exercises
  • C# Sharp Basic Exercises
  • SQL COUNT() with distinct
  • JavaScript String Exercises
  • JavaScript HTML Form Validation
  • Java Collection Exercises
  • SQL COUNT() function
  • SQL Inner Join
  • JavaScript functions Exercises
  • Python Tutorial
  • Python Array Exercises
  • SQL Cross Join
  • C# Sharp Array Exercises

We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook

Источник

Читайте также:  Html utf 8 maps
Оцените статью