I want to count the words in a specific string so that I can validate it and prevent users to write more than, for example, 100 words.
I wrote this function, but I don't think it's effective enough. I used the explode function with space as a delimiter, but what if the user puts two spaces instead of one? Can you give me a better way to do that?
function isValidLength($text , $length){
$text = explode(" " , $text );
if(count($text) > $length)
return false;
else
return true;
}
PHP substr_count() Function The substr_count() function counts the number of times a substring occurs in a string. Note: The substring is case-sensitive.
The substr_count() is a built-in function in PHP and is used to count the number of times a substring occurs in a given string. The function also provides us with an option to search for the given substring in a given range of the index. It is case sensitive, i.e., “abc” substring is not present in the string “Abcab”.
To count specific characters in string or count repeated in a string PHP, you can use PHP function substr_count().
Maybe str_word_count
could help
http://php.net/manual/en/function.str-word-count.php
$Tag = 'My Name is Gaurav';
$word = str_word_count($Tag);
echo $word;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With