Home  >  Article  >  Backend Development  >  How to count the occurrences of substrings in PHP

How to count the occurrences of substrings in PHP

青灯夜游
青灯夜游Original
2019-01-22 09:43:423631browse

PHP method to count the number of occurrences of substrings: first create an HTML sample file; then define 3 string variables; finally use the PHP built-in function substr_count() to find and count the number of occurrences of substrings That’s it.

How to count the occurrences of substrings in PHP

#The operating environment of this article: Windows 7 system, PHP version 7.1, Dell G3 computer.

In PHP, you can use the built-in function substr_count() to find and count the number of occurrences of substrings. This article will introduce you to the substr_count() function and how to use it. .

PHP substr_count() function

The substr_count() function is used to count the number of occurrences of a substring in a given string.

Basic syntax:

substr_count($str1,$str2,$start,$length);

$str1 Parameter: Indicates the specified string, required parameter.

$str2 parameter: Indicates the substring to be found, required parameter.

$start parameter: Optional parameter, indicating the position in the string to start searching for statistics.

$length parameter: optional parameter, indicating the length of the search.

Note: Substrings are case-sensitive.

Simple example:

[Related video tutorial recommendations: PHP tutorial]

Pass below Simple code example to introduce the use of substr_count() function

Example 1:

<?php 
$s1 = "PHP中文网-PHP,php,javascript,PHP"; 
$s2 = "PHP"; 
$s3 = "php"; 
$res1 = substr_count($s1, $s2); 
$res2 = substr_count($s1, $s3); 
echo("PHP出现的次数:".$res1); 
echo("<br>"); 
echo("php出现的次数:".$res2); 
?>

Output:

How to count the occurrences of substrings in PHP

Example 2: If the start and length parameters exceed the string length, the function will output a warning:

<?php 
header("content-type:text/html;charset=utf-8");
$s1 = "PHP中文网-PHP,php,javascript,PHP"; 
$s2 = "PHP"; 

$res = substr_count($s1, $s2,30,10); 
echo("PHP出现的次数:".$res); 
?>

Output:

How to count the occurrences of substrings in PHP

The above is the entire content of this article, I hope it will be helpful to everyone's study. For more exciting content, you can pay attention to the relevant tutorial columns of the PHP Chinese website! ! !

The above is the detailed content of How to count the occurrences of substrings in PHP. 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