PHP function to get the number of occurrences of a string in a file

王林
Release: 2023-02-23 14:42:02
Original
3312 people have browsed it

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)
Copy after login

Parameter description:

string     必需。规定被检查的字符串。
substring  必需。规定要搜索的字符串。
start      可选。规定在字符串中何处开始搜索。
length     可选。规定搜索的长度。
Copy after login

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个字符结束
?>
Copy after login

Running results;

3
2
1
Copy after login

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"
?>
Copy after login

2. Overlapping substrings

<?php
$str = "abcabcab";
echo substr_count($str,"abcab"); // 此函数不会对重叠的子字符串计数
?>
Copy after login

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);
?>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template