PHP count specific characters in string. Here we will learn how to count specific characters in string or how to count repeated characters in a string php.
How to count specific characters string in PHP
To count specific characters in string or count repeated in a string PHP, you can use PHP function substr_count().
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
The basic sytax of substr_count() is:
substr_count(string,substring,start,length)
Parameter
Parameter | Description |
---|---|
string | It’s required. Where find occurrences of a substring in a string PHP |
substring | It is necessary. This is a string that will be searched in the original string |
start | Optional. Specifies where in string to start searching. If negative, it starts counting from the end of the string |
length | Optional. Specifies the length of the search |
1. count specific characters in string
Suppose we have one string “php count specific characters in string php”, in this string we will count the number of times “php” occurs in string.
Let’s take an example to the count the characters or words in a string.
<?php $string = "php count specific characters in string php"; echo 'output is :- '.substr_count($string,"php"); ?>
Output
The output of the above example 1 is given below
output is :-2
Recommended Posts:
To remove specific characters from string PHP
Replace First and Last Character From String PHP
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
The output of the above example is given below
output is :-2
3. count number of character occurrences in a string in PHP without using function PHP
<?php $text="php - count number of character occurrences in a string in PHP without using function php"; $searchchar="php"; $count="0"; //zero for($i="0"; $i<strlen($text); $i=$i+1){ $str = explode(' ', $text); if($str[$i] == $searchchar){ $count=$count+1; } } echo $count ?>
Output
The output of the above example is:
output is :-2
Conclusion
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.