Counting Characters and Words in PHP

Introduction

This article explains counting characters and words in PHP. This is very useful for determine the total number of characters or total number of words in a given string. The count character use of count_chars() offers information regarding the characters found in a string. The count_chars() function's behavior depends on the optional parameter. For this explanation I will use some important PHP functions, like count_chars(), str_word_count(), and array_count_values(). Function related following the description. You can see in the following example.

Syntax

mixed count_chars(string $str [, int mode]);

 

This function returns information about a character in a string.

Example

<?php

$str = "PHP is a open source scripting and scripting language";

$fun = count_chars($str, 1);

foreach($fun as $letter=>$frequency)

{

echo "Character of \"".chr($letter)."\" present $frequency times <br />";

}

?>

Output

count2.jpg

In the next description I explain the str_word_count() function that offers information about the total number of words found in a string. When an optional parameter format is not defined, then it will return the total number of words. If the format is defined then the function's behavior is based on its string value.

Syntax

mixed str_word_count(string $str [, int format]);

This function returns information about words used in a string. The returning value depends on the mode.

Example 

<?php

$comm = <<<comm

I will explain Counting Characters and count in PHP.

This is very useful for determine the total number of characters or

total number of count in a given string. The count character use of

count_chars offers information regarding the characters found in

a string. The count_chars function it's behavior depends on how

the optional parameter.

comm;

$count = str_word_count($comm);

printf("Total count in comm: %s", $count);

?>

Output

count3.jpg

The array_count_values() function determines the frequency in which each word appears within the string. You can count all the values of an array and conjunction with array_count_values().

Example

<?php

$comm = <<<comm

I will explain Counting Characters and count in PHP.

This is very useful for determine the total number of characters or

total number of count in a given string.

comm;

$count = str_word_count($comm,2);

$arr = array_count_values($count);

echo "<pre>";print_r($arr);

?>

Output

count1.jpg