且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将 substr 过滤器从字符数转换为字数

更新时间:2023-01-29 11:32:37

使用 str_word_count

根据参数,它可以返回字符串中的单词数(默认)或找到的单词数组(以防您只想使用它们的子集).

Depending on the parameters, it can either return the number of words in a string (default) or an array of the words found (in case you only want to use a subset of them).

因此,要返回一段文本的前 100 个单词:

So, to return the first 100 words of a snippet of text:

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>';
}