• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
  • Skip to footer navigation

The Geek Diary

  • OS
    • Linux
    • CentOS/RHEL
    • VCS
  • Interview Questions
  • Database
    • MariaDB
  • DevOps
    • Docker
    • Shell Scripting
  • Big Data
    • Hadoop
    • Cloudera
    • Hortonworks HDP

PHP Function str_word_count() – Return information about words used in a string

by admin

The str_word_count() function is used to count the number of words in a string. This function was introduced in PHP4. The value of format dictates the returned value:

value returned value
0 (default) The number of words found in string
1 An array of all words found in string
2 An associative array, with keys being the positions and values being the words found at those positions in string

Syntax:

str_word_count(string $string, int $format = 0, ?string $characters = null): array|int

The str_word_count() function returns the number of words in a string. You can pass a second parameter to str_word_count() to make it do other things, but if you only pass the string parameter by itself, then it returns the number of unique words that were found in the string.

Parameters

Parameter Description
string The string
format Specify the return value of this function. (0 or 1 or 2)
characters A list of additional characters which will be considered as ‘word’

Return Values

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

Examples

Example 1:

<?php
$text = “Good morning friends! have nice day”; $a=str_word_count($text,1); $b=str_word_count($text,2); $c=str_word_count($text);
print_r($a);
print_r($b);
print $c;
?>

The output of the above program is as follows:

Array
(
[0] => Good
[1] => morning
[2] => friends
[3] => have
[4] => nice 
[5] => day )
Array
(
[0] => Good 
[5] => morning 
[13] => friends 
[22] => have 
[27] => nice 
[32] => day
)
6

Filed Under: PHP

Some more articles you might also be interested in …

  1. PHP cos function – Cosine
  2. PHP function stripslashes() – Un-quotes a quoted string
  3. PHP function str_replace() – Replace all occurrences of the search string with the replacement string
  4. PHP function str_repeat() – Repeat a string
  5. PHP base_convert function – Convert a number between arbitrary bases
  6. htaccess Cheatsheet
  7. PHP Function strncasecmp() – Binary safe case-insensitive string comparison of the first n characters
  8. PHP function chop() – Alias of rtrim()
  9. PHP function abs – Absolute value
  10. PHP ceil function – Round fractions up

You May Also Like

Primary Sidebar

Recent Posts

  • Vanilla OS 2 Released: A New Era for Linux Enthusiasts
  • mk Command Examples
  • mixxx Command Examples
  • mix Command Examples

© 2025 · The Geek Diary

  • Archives
  • Contact Us
  • Copyright