I want to count the number of words in a non-English sentence with PHP. For this I have tried str_word_count but it is not giving me the desired result, I don't want to use mb_strlen as it is giving me the length of the string. So please if someone can help me.
So, far I have done this,
function count_words($string) {
$string = html_entity_decode($string);
$string= str_replace("'", "'", $string);
$t= array(' ', "t", '=', '+', '-', '*', '/', '', ',', '.', ';', ':', '[', ']', '{', '}', '(', ')', '<', '>', '&', '%', '$', '@', '#', '^', '!', '?', '~'); // separators
$string= str_replace($t, " ", $string);
$string= trim(preg_replace("/s+/", " ", $string));
$num= 0;
if (my_strlen($string)>0) {
$word_array= explode(" ", $string);
$num= count($word_array);
}
return $num;
}
$string = "আমি 'আমার' দেশ, ভারতকে ভালবাসি";
echo count_words($string);
It needs to give me the output of 5 but giving 6, I found out that the problem is happening when i am using any comma or inverted commas, so how can i correct that also i just want to show 3 words from it. How is it possible to do.