How to count the number of occurrences of a specified character in a string in PHP

WBOY
Release: 2023-04-04 13:42:01
Original
5663 people have browsed it

This article mainly introduces how PHP counts the number of occurrences of specified characters in a string.

How to count the number of occurrences of a specified character in a string in PHP

#PHP statistics calculates the number of specified characters and all characters in a string, which is also a common test point in the PHP interview process. So for PHP beginners, it may be difficult. But as long as you master the idea of ​​​​implementing it, it is very simple.

Below we will use a simple example to introduce to you how to count the number of occurrences of a specified character in a string.

PHP code example is as follows:

<?php
$text="php.cn";
$search_char="p";
$count="0";
for($x="0"; $x< strlen($text); $x++)
{
    if(substr($text,$x,1)==$search_char)
    {
        $count=$count+1;
    }
}
echo &#39;"&#39;.$text.&#39;"&#39;."中字符".$search_char."出现的次数是:".$count.&#39;次&#39;;
Copy after login

Here we calculate the number of times the letter p appears in the string php.cn, and the output result is as follows:

How to count the number of occurrences of a specified character in a string in PHP

Of course we can count the number of times any one of the characters, such as h:

How to count the number of occurrences of a specified character in a string in PHP

Related function introduction:

strlen function means getting the string length.

substr function means returning a substring of a string. Its syntax:

string substr ( string $string , int $start [, int $length ] )
Copy after login

Returns the string string substring specified by the start and length parameters.

This article is an introduction to the method of counting the number of occurrences of specified characters in a string in PHP. It is also very simple and easy to understand. I hope it will be helpful to friends in need!

The above is the detailed content of How to count the number of occurrences of a specified character in a string in PHP. For more information, please follow other related articles on the PHP Chinese website!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!