Tutorialspoint.dev

PHP | str_word_count() Function

The str_word_count() function is a built-in function in PHP and is used to return information about words used in a string like total number word in the string, positions of the words in the string etc.

Syntax:

str_word_count ( $string , $returnVal, $chars )

Parameters Used:

  1. $string:This parameter specifies the string whose words the user intends to count.This is not an optional parameter.
  2. $returnVal:The return value of str_word_count() function is specified by the $returnVal parameter. It is an optional parameter and its default value is 0.
    The parameter can take below values as required:

    • 0 :It returns the number of words in the string $string.
    • 1 :It returns an array containing all of the words which are found in the string.
    • 2 :It returns an associative array with key-value pairs, where the key deifnes the position of the word in the string and the value is the word itself.
  3. $chars:This is an optional parameter which specifies a list of additional characters which shall be considered as a ‘word’.

Return Type: The return type of function depends on the parameter $returnVal and return the values as described above.



Below programs explain the working of str_word_count() function:

  1. Calculating the number of words in a string: To Display only the number of words in a string,the str_word_count() function should be executed in the following way:

    <?php
    $mystring = "Twinkle twinkl4e little star";
    print_r(str_word_count($mystring));
    ?>

    Output:

    5

  2. Find the words in a string: To return an array containing the words in a string,the str_word_count() function should be executed in the following way:

    <?php
    $mystring = "Twinkle twinkl4e little star";
    print_r(str_word_count($mystring, 1));
    ?>

    Output:

    Array ( [0] => Twinkle [1] => twinkl [2] => e [3] => little [4] => star )

  3. Find words in a string along with numeric position of the words: To return an array containing the words in a string along with numeric position of the words,the str_word_count() function should be executed in the following way:

    <?php
    $mystring = "Twinkle twinkl4e little star";
    print_r(str_word_count($mystring, 2));
    ?>

    Output:

    Array ( [0] => Twinkle [8] => twinkl [15] => e [17] => little [24] => star )

  4. Find words in a string when some special character are considered as word: To return an array containing the words in a string where a character shall be considered as a word, the str_word_count() function should be executed in the following way:

    <?php
    $mystring = "Twinkle twinkl4e little star";
    print_r(str_word_count($mystring, 2 ,4));
    ?>

    Output:

    Array ( [0] => Twinkle [8] => twinkl4e [17] => little [24] => star )



This article is attributed to GeeksforGeeks.org

You Might Also Like

leave a comment

code

0 Comments

load comments

Subscribe to Our Newsletter