Home > Article > Daily Programming > How to count the number of occurrences of a specified string in PHP
PHP counts the number of times a specified string appears. We can do this directly through the substr_count function in PHP. The substr_count function means counting the number of occurrences of a string.
Let’s use a simple code example to introduce PHP to count the number of occurrences of a specified string (including letters and Chinese characters):
1. The code example for counting English words is as follows:
<?php $quote = "PHP中文网,是一个学习PHP的好地方!<br>我就是在PHP中文网学习的PHP"; echo $quote; echo "<br>"; echo "<br>"; echo "以上段落中出现了".substr_count($quote,'PHP') ."次PHP!";
In the above code, the result of counting "PHP" is as follows:
2. The code example for counting the number of Chinese words is as follows:
<?php $quote = "PHP中文网,是一个学习PHP的好地方!<br>我就是在PHP中文网学习的PHP"; echo $quote; echo "<br>"; echo "<br>"; echo "以上段落中出现了".substr_count($quote,'中文网') ."次“PHP中文网”!";
In the above code, the result of counting "PHP Chinese Network" is as follows:
substr_count Syntax:
int substr_count ( string $haystack , string $needle [, int $offset = 0 [, int $length ]] )
substr_count() Returns the number of times the substring needle appears in the string haystack. Note that needle is case-sensitive.
The parameters:
haystack means searching in this string.
needle represents the string to be searched.
offset indicates the offset position where counting starts. If it is a negative number, counting starts from the end of the character.
length indicates the maximum search length after the specified offset position. If the sum of the offset plus this length is greater than the total length of the haystack, a warning message is printed. The length of a negative number is counted from the end of the haystack.
Note: This function does not calculate overlapping strings.
This article is a detailed introduction to PHP counting the number of occurrences of a specified string. It is very simple and easy to understand. I hope it will be helpful to friends in need!
The above is the detailed content of How to count the number of occurrences of a specified string in PHP. For more information, please follow other related articles on the PHP Chinese website!