PASSWORD RESET

Your destination for complete Tech news

PHP

How to count the number of words in a string in PHP?

404 0
< 1 min read

To count the number of words in a string in PHP, you can use the str_word_count() function.

This function takes a string as argument and returns the number of words in the string. By default, it counts words as contiguous sequences of characters separated by white space, punctuation, or both.

Here is an example of how to use the str_word_count() function to count the number of words in a string:

$string = "This is a test string.";
$num_words = str_word_count($string);

echo $num_words; // Outputs: 4

You can also pass a second argument to the str_word_count() function to specify a custom pattern for defining words. For example:

$string = "This is a test string.";
$num_words = str_word_count($string, 2, '.');

echo $num_words; // Outputs: 5

In this example, the second argument 2 specifies that the str_word_count() function should return an array of words instead of a count, and the third argument '.' specifies that words should be defined as sequences of characters separated by periods.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.