PHP Count Words from String Example

03-Apr-2023

.

Admin

PHP Count Words from String Example

Hi Dev,

In this example, I will show you php count words from string example. I would like to show you how to count string words in php?. This article goes in detailed on count words from string in php example. you will learn how to use function to count of words from string in php? .

There are tow example to php Count Words from string in PHP. in this example, we will use to str_word_count(),preg_split() and count() function used to count string words. so Let's both the following example with output.

Example 1: Count Words from string


index.php

<?php

$str = 'Welcome to Nicesnippets';

//Get Count Words from String

$count = str_word_count($str);

echo $count;

?>

Output:

3

Example 2: Count Words from string

index.php

<?php

$str ="Hello Developers Welcome to Our Website";

//Get Count Words from String

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

$result = count($count);

echo $result;

?>

Output:

6

I hope it could help you...

#PHP