The str_word_count() function can be used to counts the number of words in a string.

 

Syntax

str_word_count(string,return,char)
  • string – Required. Specifies the string to check
  • return – Optional. Specifies the return value of the str_word_count() perform.
    • 0 – Default. Returns the number of words found
    • 1 – Returns an array within the words from the string
    • 2 – Returns an array wherever the key’s the position of the word within the string, and value is that the actual word
  • char – Optional. Specifies special characters to be considered as words.

Example

<?php
$str = 'A good programmer looks both ways before crossing a one-way street.';
// Outputs: 11
echo str_word_count($str);
?>

Categorized in: