Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most efficient way to count all the occurrences of a specific character in a PHP string?

Tags:

string

php

What is the most efficient way to count all the occurrences of a specific character in a PHP string?

like image 305
omg Avatar asked Jun 01 '09 01:06

omg


People also ask

How do you count specific occurrences of characters in a string?

There are many ways for counting the number of occurrences of a char in a String. Let's start with a simple/naive approach: String someString = "elephant"; char someChar = 'e'; int count = 0; for (int i = 0; i < someString. length(); i++) { if (someString.

What is used to count the number of words in a string in PHP?

Approach 1: Using str_word_count() Method: The str_word_count() method is used to counts the number of words in a string.

What is Substr_count function in PHP?

The substr_count() is a built-in function in PHP and is used to count the number of times a substring occurs in a given string. The function also provides us with an option to search for the given substring in a given range of the index. It is case sensitive, i.e., “abc” substring is not present in the string “Abcab”.


1 Answers

use this:

echo substr_count("abca", "a"); // will echo 2
like image 69
Ozzy Avatar answered Sep 25 '22 10:09

Ozzy