submitted by:

PHP: count number of words in a string

Count the number of elements in a string using the count() and explode() commands. By specifying a delimiter you can also use this technique to break apart file paths and comma seperated lists.


code snippet:
<?php

$delim 
" ";
$string "One point twenty one gigawatts?";
$words count(explode($delim$string));
echo 
"The string contains $words elements.";

?>

sample output:
The string contains 5 elements.

notes:
By providing a delimiter and a string, the explode command returns an array of elements. The count command returns an integer with the number of elements in an array.