Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

figure out how many times a word comes up

Tags:

string

php

search

dogdogdogdogsdogdogdogs

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

like image 958
bkbkbk Avatar asked Dec 07 '22 04:12

bkbkbk


1 Answers

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.

like image 74
Pekka Avatar answered Dec 27 '22 09:12

Pekka