我正在使用下面的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>";}
}
PHP內置了一切功能。 – GWW
很酷,但是當我用str_word_count替換substr時,它只是返回字數。我錯過了什麼? –
嘗試以上。請注意,這不會保留標點符號(因爲它只會在單詞之間添加空格)。另一種解決方案將涉及正則表達式。 –