将 substr 过滤器从字符数转换为字数 [英] Convert substr filter from character count to word count

查看:30
本文介绍了将 substr 过滤器从字符数转换为字数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用下面的 getExcerpt() 函数来动态设置文本片段的长度.但是,我的 substr 方法目前基于字符数.我想将其转换为字数.我是否需要分离函数,或者是否有可以代替 substr 的 PHP 方法?

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 convert it to word count. Do I need to separate function or is there a PHP method that I can use in place of 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>";}
}

推荐答案

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

这篇关于将 substr 过滤器从字符数转换为字数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆