Find out how many times a word appears

dogdogdogdogsdogdogdogs

how would I calculate how many times β€œdog” and β€œdogs” appeared without regular expression?

+4
source share
5 answers

Use substr_count ()

substr_count () returns the number of times a needle substring occurs in a haystack row. Please note that the needle is case sensitive.

However , you say you want to count the occurrences of dog and dogs . If you check dogs first and then dog , you get distorted results (because dogs are counted twice).

If your example is literally dog and dogs , you need to subtract the counter for dogs from this for dog to get the correct count.

If you work with a programming approach with different words, you will need to check in advance whether any of the words is part of another word.

Welcomes SilentGhost for a simpler approach.

+10
source

Use substr_count() .

 substr_count('dogdogdogdog', 'dog'); 
+3
source

The substr_count function should do exactly what you ask:

 $str = 'dogdogdogdogsdogdogdogs'; $a = substr_count($str, 'dog'); var_dump($a); 

You'll get:

 int 7 


Print the documentation page:

 int substr_count ( string $haystack , string $needle [, int $offset = 0 [, int $length ]] ) 

substr_count() returns the number of times a substring needle occurs in a haystack string. Please note that the needle is case sensitive.

+1
source

substr_count

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

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 that Pekka mentioned in his answer . As an added benefit, you can also use str_ireplace() for case insensitive searches , then that substr_count() isn’t capable of.

From the PHP manual:

substr_count() returns the number of times a substring needle occurs in a haystack string. Please note: this needle is case sensitive.

0
source

Source: https://habr.com/ru/post/1300859/


All Articles