使用substr()截取英文字符时,会造成单词被裁剪成不完整的单词,以下提供一种避免的方法。
1 2 3 4 5 6 7 8 9 10 |
function limit_text($text, $limit) { if (str_word_count($text, 0) > $limit) { $words = str_word_count($text, 2); $pos = array_keys($words); $text = substr($text, 0, $pos[$limit]) . '...'; } return $text; } echo limit_text('Hello here is a long sentence blah blah blah blah blah hahahaha haha haaaaaa', 5); |
如果需要截取的文本中包含html的各种标签,输出时加入strip_tags(),该函数可以排除br以外的标签。
1 |
echo limit_text(strip_tags($your_text), 40); |
WordPress有自己的截取文本函数wp_trim_words(),这个用在php就好。