Word Count
This function allows you to quickly calculate how many words a string contains. Very useful for word processor scripts!
function wordcount($str) {
return count(explode(" ",$str));
}
// Example Usage:
$test = "This has four words.";
echo "There are " . wordcount($test) . " in that sentence";
?>
November 17th, 2005 at 5:42 pm
Make sure you also use array_filter function to filter out false elements when your string has double, triple or multiple spaces between words. So the function should become this:
function wordcount($str) {
return count(array_filter(explode(’ ‘, $str)));
}