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
2010-10-28 18:39:51
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
2010-10-28 18:54:05
@esryl: throws "unedefined function" error on "format_number()" but otherwise, it works! THanks.
Scott B
2010-10-28 19:04:06
@Scott np, should be number_format - i change the example code. good luck.
esryl
2010-10-28 19:07:37