olo
olo

Reputation: 5271

php length or count string

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

Answers (3)

Rozkalns
Rozkalns

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

Kasia Gogolek
Kasia Gogolek

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

Fabien M&#233;nager
Fabien M&#233;nager

Reputation: 140195

Substr_count is your friend. http://php.net/manual/en/function.substr-count.php

Upvotes: 1

Related Questions