Convert substr filter from character count to word count

后端 未结 2 1061
Happy的楠姐
Happy的楠姐 2021-01-19 06:58

I\'m using the getExcerpt() function below to dynamically set the length of a snippet of text. However, my substr method is currently based on character count. I\'d like to

2条回答
  •  感情败类
    2021-01-19 07:33

    Use 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).

    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 ''.implode(" ",$result).'';
    }
    

提交回复
热议问题