私はphp 5.3を使用していますが、検証のためにテキストの単語を数えたいと思っています。私の問題は、検証テキスト用に持っている JavaScript 機能が、php 機能に応じて異なる数の単語を返すことです。
phpコードは次のとおりです。
//trim it
$text = strip_tags(html_entity_decode($text,ENT_QUOTES));
// replace numbers with X
$text = preg_replace('/\d/', 'X', $text);
// remove ./,/-/&
$text = str_replace(array('.',',','-','&'), '', $text);
// number of words
$count = str_word_count($text);
PHP 5.5 では正しい数の単語が得られますが、php 5.3 では得られないことに気付きました。私はそれについて検索し、このリンクを見つけました ( http://grokbase.com/t/php/php-bugs/12c14e0y6q/php-bug-bug-63663-new-str-word-count-does-not-properly- handle-non-latin-characters ) で、php 5.3 のラテン文字に関するバグについて説明しています。私はこのコードでそれを解決しようとしました:
// remove non-utf8 characters
$text = preg_replace('/[^(\x20-\x7F)]*/','', $text);
しかし、まだ正しい結果が得られませんでした。基本的に、単語の数は結果に非常に近く、正確な場合もありましたが、しばしば問題がありました。
バグを修正するために、別の php 機能を作成することにしました。phpコードは次のとおりです。
//trim it
$text = strip_tags(html_entity_decode($text,ENT_QUOTES));
// replace multiple (one ore more) line breaks with a single space
$text = preg_replace("/[\n]+/", " ", $text);
// replace multiple (one ore more) spaces with a separator string (@SEPARATOR@)
$text = preg_replace("/[\s]+/", "@SEPARATOR@", $text);
// explode the separator string (@SEPARATOR@) and get the array
$text_array = explode('@SEPARATOR@', $text);
// get the numbers of the array/words
$count = count($text_array);
// check if the last key of the array is empty and decrease the count by one
$last_key = end($text_array);
if (empty($last_key)) {
$count--;
}
最後のコードは問題なく動作しています。2 つの質問をしたいと思います。
- str_word_count 関数に関する最初の状況で何ができますか?
- 私の 2 番目の解決策が正確である場合、またはそれを改善するために何かできることはありますか?