Getting the Number of Words or Characters With PHP

Need to check the number of characters in a string, perhaps for sending user input to Twitter via the API? It can be done easily by using the strlen() function, which simply returns the number of characters in the string passed to it.

$phrase = 'The quick brown fox jumped over the lazy dog.';
echo strlen($phrase);

Counting the number of words in a string variable sounds like it would be a lot harder, doesn’t it? It’s done much the same way, but with the str_word_count() function.

$phrase = 'The quick brown fox jumped over the lazy dog.';
echo str_word_count($phrase);

I hadn’t known about str_word_count() until fairly recently, but I wasn’t too surprised by its existence. PHP certainly excels at string manipulation…