0

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

1
  • 1
    Do you need to count words or substrings? For example, should 'idea' in 'idealistic' be counted too? If 'yes', choose between substr_count mentioning answers here. ) Otherwise consider using str_word_count - or its regex equivalents. Commented Sep 8, 2012 at 9:11

3 Answers 3

4

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'];
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.