Home  >  Article  >  Backend Development  >  How to find how many times a string appears in php

How to find how many times a string appears in php

青灯夜游
青灯夜游Original
2021-11-17 18:18:333961browse

Search method: 1. Use substr_count(), syntax "substr_count(string,substring)"; 2. Use mb_substr_count(), syntax "mb_substr_count(string,substring)".

How to find how many times a string appears in php

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

php search string How many times does it appear

Method 1: Use the substr_count() function

substr_count() function to count the number of times a substring appears in a string ( case-sensitive).

Syntax:

substr_count(string,substring,start,length)
  • string Required. Specifies the string to be checked.

  • #substring Required. Specifies the string to search for.​

  • #start Optional. Specifies where in the string to begin the search.

  • #length Optional. Specifies the length of the search.

Note: If the start parameter plus the length parameter is greater than the string length, this function generates a warning.

Example:

<?php
header("Content-type:text/html;charset=utf-8");
$str="I love Shanghai. Shanghai is the biggest city in china.";
$count=substr_count($str,"Shanghai");
echo "Shanghai 出现了:".$count."次";
?>

Output result:

How to find how many times a string appears in php

##Method 2: Use mb_substr_count() function

mb_substr_count() function counts the number of occurrences of a string.

Syntax:


mb_substr_count(string,substring,encoding)

  • string Required. Specifies the string to be checked.

  • #substring Required. Specifies the string to search for.

  • encoding is optional. Specifies the character encoding. If omitted or null, the internal character encoding is used.

  • <?php
    header("Content-type:text/html;charset=utf-8");
    $str="我爱上海。上海是中国最大的城市。";
    $count=mb_substr_count($str,"上海");
    echo "上海 出现了:".$count."次";
    ?>
Output results:

How to find how many times a string appears in php

Recommended learning: "

PHP Video Tutorial"

The above is the detailed content of How to find how many times a string appears 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