Count all word including numbers in a php string

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.


The following using count() and explode(), will echo:

The number 1 in this line will counted and it contains the following count 8

PHP:

<?php

$text = "The number 1 in this line will counted";

$count = count(explode(" ", $text));

echo "$text and it contains the following count $count";

?>

Edit:

Sidenote:
The regex can be modified to accept other characters that are not included in the standard set.

<?php

$text = "The numbers   1  3 spaces and punctuations will not be counted !! . . ";

$text = trim(preg_replace('/[^A-Za-z0-9\-]/', ' ', $text));

$text = preg_replace('/\s+/', ' ', $text);


// used for the function to echo the line of text
$string = $text;

    function clean($string) {

       return preg_replace('/[^A-Za-z0-9\-]/', ' ', $string);

    }

echo clean($string);

echo "<br>";

echo "There are ";
echo $count = count(explode(" ", $text));
echo " words in this line, this includes the number(s).";

echo "<br>";

echo "It will not count punctuations.";

?>

Tags:

Php