Reputation: 5271
I am working on sorting some text, I want to count how many times a certain word occurs.
the text part like
I have no idea, you got some idea, we will work out some idea, I have no idea, you got some idea, we will work out some idea, I have no idea,you got some idea, we will work out some idea
how can I use php to count how many times "idea" occurred, like word "idea" occurred 9 I am confused on count and length.
Could someone give an example please? many thanks
Upvotes: 0
Views: 853
Reputation: 512
Using like search highlighting method (modified to work your way)
<?php
$s = 'idea';
$text = "I have no idea, you got some idea, we will work out some idea, I have no idea, you got some idea, we will work out some idea, I have no idea,you got some idea, we will work out some idea";
$keys = explode(" ",$s);
$count = preg_match_all('/('. implode('|', $keys) .')/iu', $text);
echo $count;
?>
Comparing to substr_count function, this will count 'ideaidea' as two.
Upvotes: 0
Reputation: 3414
Try the script below. str_word_count() will split the sentence into array of words, and array_count_values() will assign the number of times each of them appears.
$words = str_word_count($text, 1);
$times = array_count_values($words);
echo $times['idea'];
Upvotes: 4
Reputation: 140195
Substr_count is your friend. http://php.net/manual/en/function.substr-count.php
Upvotes: 1