How to find number of words in a string in PHP

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);
?>

Praveen Kumar

I am a fullstack web developer with a passion for SEO, creating stunning websites, and organic marketing. I am a perfectionist.

Post navigation