tags:

views:

96

answers:

5

dogdogdogdogsdogdogdogs

how would I count how many times "dog" and "dogs" appeared without regex?

+7  A: 

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.

Pekka
can't you just subtract the count of the long word from the count of the short word? why all these complications?
SilentGhost
@SilentGhost of course. Thanks, edited my answer.
Pekka
@SilentGhost: It can become harder to understand if we're dealing with several overlapping strings.
Alix Axel
@Alix: hm, are we? how will this whole thing work in this case?
SilentGhost
@SilentGhost: I don't know, the example provided doesn't seem to be a real world application. I had the exact same though you did, just making a point - chill out.
Alix Axel
@Alix the point is good. It gets *real* tough with overlapping strings.
Pekka
+2  A: 

Use substr_count().

substr_count('dogdogdogdog', 'dog');
Mathias Bynens
A: 

substr_count

substr_count('dogdogdogdogsdogdogdogs', 'dog');
// returns 7
Alex Barrett
+1  A: 

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.

Pascal MARTIN
A: 

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.

Alix Axel