I want to count the words in a specific string , so I can validate it and prevent users to write more than 100 words for example .
I wrote this function but I don\'t
str_count_words has his flaws. it will count underscores as separated words like this_is two words:
You can use the next function to count words separated by spaces even if theres more than one between them.
function count_words($str){
while (substr_count($str, " ")>0){
$str = str_replace(" ", " ", $str);
}
return substr_count($str, " ")+1;
}
$str = "This is a sample_test";
echo $str;
echo count_words($str);
//This will return 4 words;
There are n-1 spaces between n objects so there will be 99 spaces between 100 words, so u can choose and average length for a word say for example 10 characters, then multiply by 100(for 100 words) then add 99(spaces) then you can instead make the limitation based on number of characters(1099).
function isValidLength($text){
if(strlen($text) > 1099)
return false;
else return true;
}
Try this:
function get_num_of_words($string) {
$string = preg_replace('/\s+/', ' ', trim($string));
$words = explode(" ", $string);
return count($words);
}
$str = "Lorem ipsum dolor sit amet";
echo get_num_of_words($str);
This will output: 5
You can use the built in PHP function str_word_count. Use it like this:
$str = "This is my simple string.";
echo str_word_count($str);
This will output 5.
If you plan on using special characters in any of your words, you can supply any extra characters as the third parameter.
$str = "This weather is like el ninã.";
echo str_word_count($str, 0, 'àáã');
This will output 6.
Using substr_count to Count the number of any substring occurrences. for finding number of words set $needle to ' '. int substr_count ( string $haystack , string $needle)
$text = 'This is a test';
echo substr_count($text, 'is'); // 2
echo substr_count($text, ' ');// return number of occurance of words
This function uses a simple regex to split the input $text on any non-letter character:
function isValidLength($text, $length) {
$words = preg_split('#\PL+#u', $text, -1, PREG_SPLIT_NO_EMPTY);
return count($words) <= $length;
}
This ensures that is works correctly with words separated by multiple spaces or any other non-letter character. It also handles unicode (e.g. accented letters) correctly.
The function returns true when the word count is less than $length.