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

Learn more

PHP Str_word_count

Reference on the str_word_count function of PHP, includes example of use, and other candy.

Edited: 2013-06-10 19:24

The str_word_count function of PHP will either count the number of words in a string, or return an array containing all the words in a string – it depends on what parameters you use with the function.

See also: Count number of words with PHP

Parameters

stringThe string Itself (doh!)
format

The format you want to have returned.

  • 0 – Returns the word count.
  • 1 – Returns an array containing all the words found inside the string itself.
  • 2 – Returns an array of words found in string, where the numeric position of each word will be used as array key value.
charlistA list of characters which will be considered as "word" by PHP.

Str_word_count example

What is an reference without code examples, right? The below script is using the charlist parameter to include a few numeric characters, these will then be considered as "word" characters together with the existing alphabetic characters.

<?php
  $str = "Thi3s is j4ust an e8ampl9e";
  print_r(str_word_count($str, 1, '3498'));
  echo "<br><br>";
  echo 'Word Count: <strong>' . str_word_count($str, 0, '3498') . '</strong>';
?>