How can setlocale() be used to address problems with str_word_count() in PHP?

The issue with str_word_count() in PHP arises when working with multibyte characters or strings in different languages. To address this problem, you can use the setlocale() function to set the appropriate locale for your script, which will enable proper handling of multibyte characters and words in different languages.

// Set the locale to handle multibyte characters
setlocale(LC_CTYPE, 'en_US.UTF-8');

// Use str_word_count() with the proper locale setting
$wordCount = str_word_count($string, 0, 'en_US.UTF-8');

// Output the word count
echo $wordCount;