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

The Geek Diary

  • OS
    • Linux
    • CentOS/RHEL
    • Solaris
    • Oracle Linux
    • VCS
  • Interview Questions
  • Database
    • oracle
    • oracle 12c
    • ASM
    • mysql
    • 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 function strcmp() – Binary safe string comparison
  2. PHP decbin function – Decimal to binary
  3. PHP function str_replace() – Replace all occurrences of the search string with the replacement string
  4. PHP connection_status function – Returns connection status bitfield
  5. PHP function bin2hex – Convert binary data into hexadecimal representation
  6. How to test a PHP script
  7. PHP Function str_split() – Convert a string to an array
  8. PHP asin function – Arc sine
  9. PHP base_convert function – Convert a number between arbitrary bases
  10. PHP Function strchr() – Alias of strstr()

You May Also Like

Primary Sidebar

Recent Posts

  • JavaFX ComboBox: Set a value to the combo box
  • Nginx load balancing
  • nginx 504 gateway time-out
  • Images preview with ngx_http_image_filter_module

© 2022 · The Geek Diary

  • Archives
  • Contact Us
  • Copyright