IT & Programming

How to count words of a text using PHP

Function uses preg_grep and preg_split expressions to calculate total number of words in a given paragraph or text.

Function

function countWords($string) {
    
    $split_array = preg_split('/\s+/', $string);      
    
    $word_count = preg_grep('/[a-zA-Z0-9\\x80-\\xff]/', $split_array);
    
    return count($word_count);
}

Calling The Function

$string = 'Only dead fish go with the flow';

echo countWords($string);

Output

7

Leave A comment

Email address is optional and will not be published. Only add email address if you want a reply from blog author.
Please fill required fields marked with *