php计算.doc、.docx中希腊字符的单词数


php count words in .doc,.docx with greek characters

我使用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);   
  }

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字符属性