tags:

views:

38

answers:

4

I would like to use php to pass a keyword phrase to a function and have the function parse a block of text and return the keyword density of the input phrase as a percentage of the total word count of the text block.

A: 

How about:

  • Split the input text on spaces to get a array of words using preg_split.
  • Use count function to get the total number of words.
  • Use the array_count_values function to get the number of time the keyword appears.
  • Calculate ratio of previous two computed values.

You'll have to filter the input text by removing punctuations before you split it.

codaddict
A: 

Check out:

Sarfraz
A: 

Take a look at:

evolve
A: 
$text = 'lorem ipsum etc';
$keyword = 'lorem ipsum';

$word_count = explode(' ', $text);
$word_count = count($word_count);

$keyword_count = preg_match_all("#{$keyword}#si", $text, $matches);
$keyword_count = count($matches);

$density = $keyword_count / $word_count * 100;

echo number_format($density, 2) . '%';
esryl
@esryl: throws "unedefined function" error on "format_number()" but otherwise, it works! THanks.
Scott B
@Scott np, should be number_format - i change the example code. good luck.
esryl