Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to count the words in a specific string in PHP?

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;
}
like image 824
Waseem Senjer Avatar asked Jan 24 '11 20:01

Waseem Senjer


People also ask

How do I count the number of letters in a string in PHP?

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.

What is Substr_count function in PHP?

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”.

How do I count the number of repeated characters in a string in PHP?

To count specific characters in string or count repeated in a string PHP, you can use PHP function substr_count().


1 Answers

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;
like image 75
Francesco Laurita Avatar answered Oct 03 '22 02:10

Francesco Laurita