Extract Keywords From A Text String With PHP
A common issue I have come across in the past is that I have a CMS system, or an old copy of Wordpress, and I need to create a set of keywords to be used in the meta keywords field. To solve this I put together a simple function that runs through a string and picks out the most commonly used words in that list as an array. This is currently set to be 10, but you can change that quite easily.
The first thing the function defines is a list of "stop" words. This is a list of words that occur quite a bit in English text and would therefore interfere with the outcome of the function. The function also uses a variant of the slug function to remove any odd characters that might be in the text.
function extractCommonWords($string){
$stopWords = array('i','a','about','an','and','are','as','at','be','by','com','de','en','for','from','how','in','is','it','la','of','on','or','that','the','this','to','was','what','when','where','who','will','with','und','the','www');
$string = preg_replace('/\s\s+/i', '', $string); // replace whitespace
$string = trim($string); // trim the string
$string = preg_replace('/[^a-zA-Z0-9 -]/', '', $string); // only take alphanumerical characters, but keep the spaces and dashes too…
$string = strtolower($string); // make it lowercase
preg_match_all('/\b.*?\b/i', $string, $matchWords);
$matchWords = $matchWords[0];
foreach ( $matchWords as $key=>$item ) {
if ( $item == '' || in_array(strtolower($item), $stopWords) || strlen($item) <= 3 ) {
unset($matchWords[$key]);
}
}
$wordCountArr = array();
if ( is_array($matchWords) ) {
foreach ( $matchWords as $key => $val ) {
$val = strtolower($val);
if ( isset($wordCountArr[$val]) ) {
$wordCountArr[$val]++;
} else {
$wordCountArr[$val] = 1;
}
}
}
arsort($wordCountArr);
$wordCountArr = array_slice($wordCountArr, 0, 10);
return $wordCountArr;
}
The function returns the 10 most commonly occurring words as an array, with the key as the word and the amount of times it occurs as the value. To extract the words just use the implode() function in conjunction with the array_keys() function. To change the number of words returned just alter the value in the third parameter of the array_slice() function near the return statement, currently set to 10. Here is an example of the function in action.
$text = "This is some text. This is some text. Vending Machines are great.";
$words = extractCommonWords($text);
echo implode(',', array_keys($words));
This produces the following output.
some,text,machines,vending
Comments
split a command stored in a variable
I would love to help but I'm
the script doesnt want to work:(:( and it is exactly what i need
Thanks for the input
Do you maybe know, what would
Are you passing it a HTML
Tit for tat
$wordCountArray = array_count_values( $matchWords );No need of a foreach loop. Thestrtolower()call inside both foreach loops is really not needed either since you have already converted $string to lowercase beforehand.Help calling a certain key of the array
follow up
@Guillermo I think to get the
function extractCommonWords($string){ $stopWords = array('i','a','about','an','and','are','as','at','be','by','com','de','en','for','from','how','in','is','it','la','of','on','or','that','the','this','to','was','what','when','where','who','will','with','und','the','www'); $string = preg_replace('/ss+/i', '', $string); $string = trim($string); // trim the string $string = preg_replace('/[^a-zA-Z0-9 -]/', '', $string); // only take alphanumerical characters, but keep the spaces and dashes too… $string = strtolower($string); // make it lowercase preg_match_all('/\b.*?\b/i', $string, $matchWords); $matchWords = $matchWords[0]; $totalWords = count($matchWords[0]); foreach ( $matchWords as $key=>$item ) { if ( $item == '' || in_array(strtolower($item), $stopWords) || strlen($item) <= 3 ) { unset($matchWords[$key]); } } $wordCountArr = array(); if ( is_array($matchWords) ) { foreach ( $matchWords as $key => $val ) { $val = strtolower($val); if ( !isset($wordCountArr[$val]) { $wordCountArr[$val] = array(); } if ( isset($wordCountArr[$val]['count']) ) { $wordCountArr[$val]['count']++; } else { $wordCountArr[$val]['count'] = 1; } } arsort($wordCountArr); $wordCountArr = array_slice($wordCountArr, 0, 10); foreach ( $wordCountArr as $key => $val) { $wordCountArr[$val]['bytotal'] = $wordCountArr[$val]['count'] / $totalWords; } } return $wordCountArr; }This is untested code, but it should get you what you need. :)Hey thanks for your
Excellent Code Example
if ( $item == '' || in_array($item, $stopWords) || strlen($item) <= 3 ) {2) Added a $count parameter to the function so that when it is called you can specify how many words to return.function extractCommonWords($string,$count){ ... $wordCountArr = array_slice($wordCountArr, 0, $count); return $wordCountArr; }The hardest thing to get right is the stop word list.Brill
Brilliant. Thanks for this piece of code. I was after doing something very similar so have used this as a base and made a few tweaks here and there so it fits my needs.
Removing ss from words
Hi
Great code and is working a treat on my site but I have a problem with words containing 'ss'. The double ss is being removed so a word such as 'password' is being seen as 'paword' in the keywords.
Regards
Please help me with spanish letters
Hi, would you please to let me know how I could include spanish characters too?.
For example I need to print: 'tamaño' instead I get: 'tamao'
Thanks in advance
Tolenca
You need to add those special
You need to add those special characters to the regular expression on line 6 of the examples above. You just need to make sure it takes alphanumeric characters as well as the spanish letters. I think that should work.
instead of$wordCountArr =
instead of
$wordCountArr=array();if ( is_array($matchWords) ) { foreach ( $matchWords as $key => $val ) { $val = strtolower($val); if ( !isset($wordCountArr[$val]) { $wordCountArr[$val] = array(); } if ( isset($wordCountArr[$val]['count']) ) { $wordCountArr[$val]['count']++; } else { $wordCountArr[$val]['count'] = 1; } }I did:$ignoreOccur = array(1,2); $wordCountArr = array_diff(array_count_values(explode(" ", matchWords)), $ignoreOccur);To get all assoc array $wordCoundArr of [word] => [occurences], ignoring words that have occurred 1 or 2 (or specified number of) times.Interesting take on it. I
Interesting take on it. I like it! :)
Also remove numbers
I changed line 13 to not include 'keywords' that are just numbers using the is_numeric() function
if ( $item == '' || in_array($item, $stopWords) || strlen($item) <= 3 || is_numeric($item) ) {useful code
Thanks, this is quite useful!
Post new comment