PHP Count Specific Characters in String

Count specific or repeated characters in string in PHP; Through this tutorial, i am going to show you how to count specific characters in string or how to count repeated characters in a string php.

How to count specific or repeated characters in a string PHP

Using PHP function substr_count(), you can count specific characters in string or count repeated in a string PHP.

PHP substr_count() Function

The substr_count() function is an inbuilt PHP function that can be used to counts the number of times a substring occurs in a string.

Syntax of PHP substr_count() Function

The basic sytax of substr_count() is:

substr_count(string,substring,start,length)

Parameter of PHP substr_count() Function

ParameterDescription
stringIt’s required. Where find occurrences of a substring in a string PHP
substringIt is necessary. This is a string that will be searched in the original string
startOptional. Specifies where in string to start searching. If negative, it starts counting from the end of the string
lengthOptional. Specifies the length of the search

Example 1 – count specific characters in string

Let you have specific characters in string; And want to count the characters or words in a PHP string. So, you can use the following example to count specific or repeated characters from string in PHP; is as follows:

<?php
$string = "php count specific characters in string php"; 
echo 'output is :- '.substr_count($string,"php");
?>

Output of the above given Code; is as follows:

 output is :-2

Example 2 – find all occurrences of a substring in a string PHP

To find all occurrences of a substring in string PHP. You can see the below example for that:

<?php 
// PHP program to count number of times 
// sub-string appears in original string. 
  
$originalStr = "how to count sub-string in string PHP"; 
$subString = "string"; 
  
$res = substr_count($originalStr, $subString); 
  
echo($res); 
?> 

Output of the above given Code; is as follows:

 output is :-2

Conclusion

Count specific or repeated character from string in PHP’ In this tutorial, you have learned how to count substring in string PHP by using substr_count and without using substr_count() function in PHP.

Recommended PHP Tutorials

Leave a Comment