To count words in a php string usually we can use str_word_count but I think not always a good solution
$var =\"Hello world!\";
echo str_
Just some improvement your solution
function stringWordNumberCount($text){
if (!$text) {
return 0;
}
//Clean the text to remove special character
$text = trim(preg_replace('/[^A-Za-z0-9\-]/', ' ', $text));
//Remove continus space on text
$text = trim( preg_replace('/\s+/', ' ',$text));
//count space
return count(explode(' ', $text));
}