Home  >  Article  >  Backend Development  >  PHP function to get the number of occurrences of a string in a file

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

王林
王林Original
2019-09-03 09:50:173172browse

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:

";
 echo substr_count($str,"脚本",16);//指定在第16个字符后开始搜索
 echo "
"; echo substr_count($str,"脚本",16,10);//指定从第16个字符开始往后搜索10个字符结束 ?>

Running results;

3
2
1

More examples:

1. Use all parameters

"; // 使用 strlen() 来返回字符串长度
echo substr_count($str,"is")."
"; // 字符串中 "is" 出现的次数 echo substr_count($str,"is",2)."
"; // 字符串缩减为 "is is nice" echo substr_count($str,"is",3)."
"; // 字符串缩减为 "s is nice" echo substr_count($str,"is",3,3)."
"; // 字符串缩减为 "s i" ?>

2. Overlapping substrings

3. If the start and length parameters exceed the string length, output a warning

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!

Statement:
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