【发布时间】:2016-02-29 03:47:34
【问题描述】:
我正在寻找可以从文本字符串自动创建关键字的代码。下面的代码适用于拉丁字符,但如果我尝试将它与俄语(西里尔文)一起使用 - 结果只是逗号之间有空格。
我不确定问题出在哪里,但我相信它与编码有关。我试图用这个
对字符串进行编码$string = preg_replace('/\s\s+/i', '', mb_strtolower(utf8_encode($string)));
但没有运气。结果是一样的。
另外,我在 $stopwords var 中只包含俄语单词
$stopWords = array('у','ни','на','да','и','нет','были','уже','лет','в','что','их','до','сих','пор','из','но','бы','чтобы','вы','была','было','мы','к','от','с','так','как','не','есть','ее','нам','для','вас','о','них','без');
这是原始代码
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;}
任何帮助将不胜感激。
【问题讨论】:
标签: php regex preg-replace preg-match-all