我使用的是PHP 5.3,我想爲驗證原因計算一些文本的字數。 我的問題是,我有驗證文本的JavaScript功能,根據PHP功能返回不同數量的單詞。str_word_count沒有正確處理非拉丁字符
這裏是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功能來修復這個bug。這裏是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 (@[email protected])
$text = preg_replace("/[\s]+/", "@[email protected]", $text);
// explode the separator string (@[email protected]) and get the array
$text_array = explode('@[email protected]', $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--;
}
最後的代碼工作對我罰款,我想請教兩個問題:
- 我能在第一種情況下做一下str_word_count功能是什麼?
- 如果我的第二個解決方案是準確的,或者我可以做些改進嗎?
的可能重複:HTTP:// stackoverflow.com/questions/8290537/is-php-str-word-count-multibyte-safe – AJReading
我想指出我們的正則表達式' \ s'匹配換行符'\ n',即將換行符視爲空白字符的子集。 – ThorSummoner