Extract Keywords From A Text String With PHP

28/02/2022  •  159 views
 
<?php
function extractKeyWords($string) {
 mb_internal_encoding('UTF-8');
 $stopwords = array();
 $string = preg_replace('/[\pP]/u', '', trim(preg_replace('/\s\s+/iu', '', mb_strtolower($string))));
 $matchWords = array_filter(explode(' ',$string) , function ($item) use ($stopwords) { return !($item == '' || in_array($item, $stopwords) || mb_strlen($item) <= 2 || is_numeric($item));});
 $wordCountArr = array_count_values($matchWords);
 arsort($wordCountArr);
 return array_keys(array_slice($wordCountArr, 0, 10));
}

print implode(',', extractKeyWords("This is some text. This is some text. Vending Machines are great."));
// prints "this,text,some,great,are,vending,machines"
?>
 English / Indonesian