2011-06-20 32 views
3

我正在使用下面的getExcerpt()函數動態設置一段文本的長度。但是,我的substr方法目前基於字符數。我想將其轉換爲字數。我需要單獨的函數還是有一個PHP方法,我可以用來代替substr?將substr過濾器從字符數轉換爲字數

function getExcerpt() 
{ 
    //currently this is character count. Need to convert to word count 
    $my_excerptLength = 100; 
    $my_postExcerpt = strip_tags(
     substr(
      'This is the post excerpt hard coded for demo purposes', 
      0, 
      $my_excerptLength 
      ) 
     ); 
    return ": <em>".$my_postExcerpt." [...]</em>";} 
} 

回答

4

使用str_word_count

根據不同的參數,它可以返回的單詞數在一個字符串(默認)或發現的單詞的數組(如果你只想使用的一個子集他們)。

所以,回到文本片段的第100個話:

function getExcerpt($text) 
{ 
    $words_in_text = str_word_count($text,1); 
    $words_to_return = 100; 
    $result = array_slice($words_in_text,0,$words_to_return); 
    return '<em>'.implode(" ",$result).'</em>'; 
} 
+0

PHP內置了一切功能。 – GWW

+0

很酷,但是當我用str_word_count替換substr時,它只是返回字數。我錯過了什麼? –

+1

嘗試以上。請注意,這不會保留標點符號(因爲它只會在單詞之間添加空格)。另一種解決方案將涉及正則表達式。 –

1

如果你想你的腳本不應該忽視的週期,逗號和其他標點符號,那麼你應該採用這種方式。

function getExcerpt($text) 
{ 
    $my_excerptLength = 100; 
    $my_array = explode(" ",$text); 
    $value = implode(" ",array_slice($my_array,0,$my_excerptLength)); 
    return 

} 

注意:這僅僅是一個例子,希望它能幫助你。如果它對你有幫助,不要忘記投票。