开发者

figure out how many times a word comes up

dogdogdogdogsdogdogdogs

how would I开发者_JAVA技巧 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.


Use substr_count().

substr_count('dogdogdogdog', 'dog');


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.


substr_count

substr_count('dogdogdogdogsdogdogdogs', 'dog');
// returns 7


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜