Home > Article > Backend Development > PHP function to get the number of occurrences of a string in a file
This article will give you an example of how to get the number of occurrences of a string with substr_count() in PHP, and share it with you for your reference!
substr_count() in PHP can be used to count the number of occurrences of a substring in a specified string.
substr_count()
The function is defined as follows:
substr_count(string,substring,start,length)
Parameter description:
string 必需。规定被检查的字符串。 substring 必需。规定要搜索的字符串。 start 可选。规定在字符串中何处开始搜索。 length 可选。规定搜索的长度。
Example:
<?php $str="脚本之家提供大量脚本代码及脚本特效下载"; echo substr_count($str,"脚本"); echo "<br/>"; echo substr_count($str,"脚本",16);//指定在第16个字符后开始搜索 echo "<br/>"; echo substr_count($str,"脚本",16,10);//指定从第16个字符开始往后搜索10个字符结束 ?>
Running results;
3 2 1
More examples:
1. Use all parameters
<?php $str = "This is nice"; echo strlen($str)."<br>"; // 使用 strlen() 来返回字符串长度 echo substr_count($str,"is")."<br>"; // 字符串中 "is" 出现的次数 echo substr_count($str,"is",2)."<br>"; // 字符串缩减为 "is is nice" echo substr_count($str,"is",3)."<br>"; // 字符串缩减为 "s is nice" echo substr_count($str,"is",3,3)."<br>"; // 字符串缩减为 "s i" ?>
2. Overlapping substrings
<?php $str = "abcabcab"; echo substr_count($str,"abcab"); // 此函数不会对重叠的子字符串计数 ?>
3. If the start and length parameters exceed the string length, output a warning
<?php echo $str = "This is nice"; substr_count($str,"is",3,9); ?>
because of the length The value exceeds the length of the string (3 9 is greater than 12), and a warning will be output.
For more related questions, please visit the PHP Chinese website: PHP Video Tutorial
The above is the detailed content of PHP function to get the number of occurrences of a string in a file. For more information, please follow other related articles on the PHP Chinese website!