dogdogdogdogsdogdogdogs
how would I count how many times "dog" and "dogs" appeared without regex?
dogdogdogdogsdogdogdogs
how would I count how many times "dog" and "dogs" appeared without regex?
Use substr_count()
substr_count() returns the number of times the needle substring occurs in the haystack string. Please note that needle is case sensitive.
However, you say you want to count the occurrences of dog
and dogs
. If you check for dogs
first and then for dog
, you will get skewed results (because dogs
gets counted twice).
If your example is literally dog
and dogs
, you need to subtract the count for dogs
from that for dog
to get the proper count.
If you are working on a programmatic approach with varying words, you will need to check beforehand whether any of the words are a part of another word.
Cheers to SilentGhost for the simpler approach.
The substr_count
function should do just what you're asking :
$str = 'dogdogdogdogsdogdogdogs';
$a = substr_count($str, 'dog');
var_dump($a);
Will get you :
int 7
Quoting its documentation page :
int substr_count ( string $haystack , string $needle
[, int $offset = 0 [, int $length ]] )
substr_count()
returns the number of times the needle substring occurs in the haystack string. Please note that needle is case sensitive.
Well, besides substr_count()
you can also use the good old str_replace()
:
$string = 'dogdogdogdogsdogdogdogs';
$str = str_replace('dogs', '', $string, $count);
echo 'Found ' . $count . ' time(s) "dogs" in ' . $string;
$str = str_replace('dog', '', $str, $count);
echo 'Found ' . $count . ' time(s) "dog" in ' . $string;
This approach solves the problem Pekka mentioned in his answer. As an added benefit you can also use str_ireplace()
for case insensitive search, something that substr_count()
isn't capable of.
From the PHP Manual:
substr_count()
returns the number of times the needle substring occurs in the haystack string. Please note that needle is case sensitive.