By using this site you agree to the use of cookies by Brugbart and our partners.

Learn more

Count number of words with PHP

PHP tutorial on how to count the number of words in a string.

Edited: 2014-12-28 04:00

This tutorial will show you how to count the number of words in a string using PHP. Counting the number of words is not exactly easy, as it will depend on which characters are considered separators. For many languages, the str_word_count function will however be sufficient, and this is also the function that we will be using in this PHP tutorial.

The str_word_count function will count words in a string. Valid words will only contain alphabetic characters, which may contain but not start with "'" and "-" characters.

The below script will return the number of words found in the $str variable.

The above script should count 18 words, as word-count will count as one word.

Return an array of words in a string

It can sometimes also be useful to know how to return an array containing all the words in the string, one way to do that, is by using a parameter value of 1 instead of 0. We will be using a while loop in this tutorial, to return each word one by one. Example follows:

The above should be a useful reference. You can easily change the loop to do whatever you want to have done with the words.