Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count all word including numbers in a php string

Tags:

php

To count words in a php string usually we can use str_word_count but I think not always a good solution

good example:

$var ="Hello world!";
echo str_word_count($str);
print_r(str_word_count($str, 1));

-->output

   2
   Array ( [0] => Hello [1] => world ) 

bad example:

$var ="The example number 2 is a bad example it will not 
count numbers  and punctuations !!";

-->output:

  14
  Array ( [0] => The [1] => example [2] => number [3] => is [4] => a
  [5] => bad [6] => example [7] => it [8] => will [9] => not 
  [10] => count [11] => numbers [12] => and [13] => punctuations ) 

Is there a good predefined function to do this properly or do I have to use preg_match() ?

like image 200
Amani Ben Azzouz Avatar asked Oct 24 '14 14:10

Amani Ben Azzouz


People also ask

Which PHP string function counts the number of words in a string?

Approach 1: Using str_word_count() Method: The str_word_count() method is used to counts the number of words in a string.


1 Answers

You can always split your string by whitespace and count the results:

$res = preg_split('/\s+/', $input);
$count = count($res);

With your string

"The example number 2 is a bad example it will not 
count numbers  and punctuations !!"

This code will produce 16.

The advantage of using this over explode(' ', $string) is that it will work on multi-line strings as well as tabs, not just spaces. The disadvantage is that it's slower.

like image 75
Aleks G Avatar answered Oct 21 '22 08:10

Aleks G