burger menu icon
WillMaster

WillMaster > Library > Website Development and Maintenance

FREE! Coding tips, tricks, and treasures.

Possibilities weekly ezine

Get the weekly email website developers read:

 

Your email address

name@example.com
YES! Send Possibilities every week!

Count Specific Characters in a String

The PHP substr_count() function counts how many times specified characters occur in a string.

In other words, it can tell you how many times "stan" occurs in a word or sentence. Or how many times "a" occurs.

As examples, substr_count("substantial","stan") returns the number 1 and substr_count("substantial","a") returns the number 2. There is only one occurrence of "stan" in the string "substantial." And there are two occurrences of "a" in that string.

My use of substr_count() generally is to determine if an amount contains exactly one period, a percentage contains a "%" character, or an email address contains exactly one "@" character. Those types of things. But its use surely is not limited to that.

Here is code to fact-check the above examples.

<?php
$string='substantial';
echo '<hr>"stan" occurs '. substr_count($string,"stan") ." time in \"$string.\"";
echo '<hr>"a" occurs '. substr_count($string,"a") ." times in \"$string.\"<hr>";
?>

The above code replies with:


"stan" occurs 1 time in "substantial."
"a" occurs 2 times in "substantial."

This is the format:

substr_count(STRING,KEY)

STRING is the string to search. KEY is the character sequence to search for.

If STRING is "abacadabra" and KEY is "ab" then substr_count() returns the number 2. Proof:

<?php
$string='abacadabra';
$key = "ab";
$value = substr_count($string,$key);
echo "<hr>\"$key\" occurs times in \"$string.\"<hr>";
?>

"ab" occurs 2 times in "abacadabra."

When you need a count of how many times specific characters occur in a string, the PHP substr_count() function is available.

(This content first appeared in Possibilities newsletter.)

Will Bontrager

Was this article helpful to you?
(anonymous form)

Support This Website

Some of our support is from people like you who see the value of all that's offered for FREE at this website.

"Yes, let me contribute."

Amount (USD):

Tap to Choose
Contribution
Method

All information in WillMaster Library articles is presented AS-IS.

We only suggest and recommend what we believe is of value. As remuneration for the time and research involved to provide quality links, we generally use affiliate links when we can. Whenever we link to something not our own, you should assume they are affiliate links or that we benefit in some way.

How Can We Help You? balloons
How Can We Help You?
bullet Custom Programming
bullet Ready-Made Software
bullet Technical Support
bullet Possibilities Newsletter
bullet Website "How-To" Info
bullet Useful Information List

© 1998-2001 William and Mari Bontrager
© 2001-2011 Bontrager Connection, LLC
© 2011-2026 Will Bontrager Software LLC