2011-06-29 34 views
1

我正在嘗試爲我的網頁構建關鍵字,並且希望從文本中提取關鍵字。 我有一個功能從php中的文本中提取西里爾字詞/關鍵字

function extractCommonWords($string){ 
    $stopWords = array('и', 'или'); 

     $string = preg_replace('/ss+/i', '', $string); 
     $string = trim($string); 
     $string = preg_replace('/[^a-zA-Z0-9 -]/', '', $string); 
     $string = strtolower($string); 
     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; 
} 

這裏是我的嘗試:

$text = "Текст кирилица"; 
$words = extractCommonWords($text); 
echo implode(',', array_keys($words)); 

問題是與西裏爾字母dosen`t工作。如何解決這個問題?

回答

1

看到自己的模式來代替也將刪除所有西里爾文字符,因爲a-z不匹配。

一下添加到字符類,以保持西裏爾字母:

\p{Cyrillic} 

...並使用modifiier u喜歡通過GolezTrol建議。

$string = preg_replace('/[^\p{Cyrillic} a-zA-Z0-9 -]/u', '', $string); 

如果你只喜歡提取西里爾的話,你並不需要更換什麼,就用這個來匹配的話:

preg_match_all('/\b(\p{Cyrillic}+)\b/u', $string, $matchWords);