How to get the length of string and number of words in PHP
  John Mwaniki /   08 Sep 2021

How to get the length of string and number of words in PHP

In this article, you will learn how to get the length of a string, the number of words it contains, and the number of occurrences a character, word, or phrase appears in a string using PHP.

Getting the length of a PHP string

The strlen() function is used to get the length of a string. It returns an integer value; the length of a string(number of characters and spaces) on success, or 0 if the string is empty.

Syntax


strlen(string)

Example:

<?php
$string = "Hello World!";
$length = strlen($string);
echo $length; //Output: 12
echo "<br>";

$string2 = "I love programming";
$length2 = strlen($string2);
echo $length2; //Output: 18
?>

 

Getting the number of words in a string

The PHP str_word_count() function is used to get the number of words in a string.

Syntax


str_word_count(string)

Example:

<?php
$string = "Hello World!";
$words = str_word_count($string);
echo $words; //Output: 2
echo "<br>";

$string2 = "I love programming";
$words2 = str_word_count($string2);
echo $words2; //Output: 3
?>

 

Getting the number of occurrences of a character, word, or phrase in a string

A substring in PHP is a part of a string. It can be a single character, a word, or a number of words.

In PHP, we use the substr_count() function to get the number of times a substring occurs in a string.

Syntax


substr_count(string,substring,start,length)

Parameter Values

Parameter Description
string A mandatory parameter that specifies the string to check.
substring Mandatory parameter specifying the text to such for.
start Optional parameter that specifies where to start searching from in the string. If it is negative, it starts counting from the end of the string.
length An optional parameter specifying the length of the search.

Example:

<?php
$string = "Hello dev! I like web development.";
echo substr_count($string,"dev");
//Output: 2 because "dev" appears twice in the string
echo "<br>";

echo substr_count($string,"dev",0,10);
//Output: 1 because "dev" appears once in the first 10 characters
echo "<br>";

echo substr_count($string,"dev",0,5);
//Output: 0 because "dev" appears doesn't occur in the first 5 characters
?>

Note: This function does not count overlapped substrings.

Example

<?php
$string = "xyzxyzxy";
echo substr_count($string,"xyzx");
//Output: 1
?>

From the above example, though the substring "xyzx" appears twice in the string, it is overlapping and hence can't be counted twice.

Note: The substring is case-sensitive. ABC and abc are two different things.

Conclusion

In this article, you have learned how to get the total number of characters in a string, the number of words, and the number of substring occurrences in a string using PHP.