2014-03-31 27 views
0

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

最後的代碼工作對我罰款,我想請教兩個問題:

  1. 我能在第一種情況下做一下str_word_count功能是什麼?
  2. 如果我的第二個解決方案是準確的,或者我可以做些改進嗎?
+0

的可能重複:HTTP:// stackoverflow.com/questions/8290537/is-php-str-word-count-multibyte-safe – AJReading

+0

我想指出我們的正則表達式' \ s'匹配換行符'\ n',即將換行符視爲空白字符的子集。 – ThorSummoner

回答

0
  1. 假設你問如何仍然使用str_word_count:你湊ld嘗試使用:preg_replace('/[^a-zA-Z0-9\s]/','',$string)已經替換任何標點符號後。沒有你認識的「測試字符串」失敗,我無法嘗試,但至少這是你可以嘗試的東西。

  2. 一個改進,將實際上修剪文本,它提到第一條評論修剪,但第一行只是刪除HTML標籤。添加trim($string)那麼你可以刪除最後一個部分:

CHANGE第2行:

//trim it & remove tags 
$text = trim(strip_tags(html_entity_decode($text,ENT_QUOTES))); 

刪除:

// 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--; 
} 
0

;你有沒有考慮用正則表達式分割來計算單詞的數量,用你自己定義的單詞是什麼。我可能會推薦/ [^ \ s] + /作爲'單詞',這意味着要在/ \ s /上分割並計算'單詞'的結果數組。

PHP:讓$input = 'your input here'然後count(pregsplit('/\s/', $input))

JS:讓var input = 'your input here'然後input.split(/\s/).length

您還可以使用正則表達式字符範圍捕捉到一組字符要使用的有效的字contense,更多的正則表達式在這裏:http://www.geocities.jp/kosako3/oniguruma/doc/RE.txt