php计算.doc中的单词,带有希腊字符的.docx

时间:2015-02-16 12:11:54

标签: php unicode docx doc

我正在使用php构建一个Web应用程序,我必须计算上传的.doc或.docx文件的单词。 到目前为止,我使用上述函数来计算单词,但此代码不适用于希腊字符

表示.doc

 public static function docWordCount($file){
  $fileHandle = fopen($file, "r");
  $line = @fread($fileHandle, filesize($file));   
  $lines = explode(chr(0x0D),$line);
  $outtext = "";
  foreach($lines as $thisline)
    {
      $pos = strpos($thisline, chr(0x00));
      if (($pos !== FALSE)||(strlen($thisline)==0))
        {
        } else {
          $outtext .= $thisline." ";
        }
    }
   $outtext = preg_replace("/[^a-zA-Z0-9\s\,\.\-\n\r\t@\/\_\(\)]/","",$outtext);
  return str_word_count($outtext);
 }

和.docx:

  public static function docxWordCount($file){ 
    $striped_content = '';
    $content = '';

    $zip = zip_open($file);

    if (!$zip || is_numeric($zip)) return false;

    while ($zip_entry = zip_read($zip)) {

        if (zip_entry_open($zip, $zip_entry) == FALSE) continue;

        if (zip_entry_name($zip_entry) != "word/document.xml") continue;

        $content .= zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));

        zip_entry_close($zip_entry);
    }// end while

    zip_close($zip);

    $content = str_replace('</w:r></w:p></w:tc><w:tc>', " ", $content);
    $content = str_replace('</w:r></w:p>', "\r\n", $content);
    $striped_content = strip_tags($content);

    return str_word_count($striped_content);   
  }

1 个答案:

答案 0 :(得分:-1)

str_word_count似乎不是二进制安全的,这意味着它不支持UTF-8字符。您最好的选择是使用preg_match使用\P{L}属性将文字拆分为非单词字符。例如,以下正则表达式将在每个非字母字符中分割文本:

preg_split('/\P{L}/usi', $str, -1, , PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);

有关详细信息,请参阅Unicode character properties

相关问题