Welcome to WebmasterWorld Guest from

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

How can I count number of matches?

I am sure someone will know this right off the bat, google failed me



2:31 am on Jan 1, 2008 (gmt 0)

5+ Year Member

I have a string such as William Black Black. I want to count how many times Black is in the string. How can I do this easily?

Thanks ahead of time. I tried a couple things I thought may work but it didn't.


3:09 am on Jan 1, 2008 (gmt 0)

5+ Year Member

There are many ways to 'skin this cat', it just depends how it fits with the rest of the stuff you are doing.
Probably easiest way to accomplish this , if you are using PHP 5, is to use str_replace [php.net]

as example on that page shows, you will not end up replacing anything in the string, just make use of count.
You want to find "ll" , but don't want to replace it with anything ("") in this string "good golly miss molly!", and setting $count to return number of occurances

// Use of the count parameter is available as of PHP 5.0.0
$str = str_replace("ll", "", "good golly miss molly!", $count);
echo $count; // 2

I am not sure if you want to be case sensitive.

Another way to do this is to separate your big string into individual stings, put them in the array, and then search array for your particular value and keeping count...

There are also few other ways to do it , utilizing only string functions or combining them with array functionality, but it really depends of how this part of the code fits with everything else.

Oh, and php.net [php.net] is your friend...


5:23 pm on Jan 1, 2008 (gmt 0)

WebmasterWorld Senior Member dreamcatcher is a WebmasterWorld Top Contributor of All Time 10+ Year Member

If you want to read the string into an array use str_word_count [uk3.php.net]

You can also use substr_count [uk3.php.net] for a string count:

$string = 'William Black Black';

echo substr_count($string, 'Black'); // 2



6:29 pm on Jan 1, 2008 (gmt 0)

WebmasterWorld Senior Member 5+ Year Member

Assuming you dont already know the string, or the duplicate value, you could use something like -

$string = 'Mary had a a little lamb, she she tied it it it to a pylon, 3000 volts whent up its ... and turned its wool to nylon';
$words = explode(' ', $string);
$duplicates = array_unique($words);
$count = array();
foreach ($words as $word) {
foreach ($duplicates as $duplicate) {
if ($word == $duplicate) {
foreach ($count as $k => $v) {
if ($v > 1) {
$c = $v-1; // as a count of 1 is the first occurance
echo "$k was duplicated $c times<br />\n";

You get -
a was duplicated 2 times
she was duplicated 1 times
it was duplicated 2 times

Removed the stupid bits that I originally posted. Thats stupid code...not just stupid, in case you are wandering ;)

[edited by: PHP_Chimp at 7:19 pm (utc) on Jan. 1, 2008]


Featured Threads

Hot Threads This Week

Hot Threads This Month