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

发布于 2024-11-16 11:15:27 字数 520 浏览 6 评论 0原文

我使用下面的 getExcerpt() 函数来动态设置文本片段的长度。但是,我的 substr 方法目前基于字符计数。我想将其转换为字数。我是否需要分离函数,或者是否有可以使用 PHP 方法来代替 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>";}
}

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

若能看破又如何 2024-11-23 11:15:27

使用 str_word_count

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

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

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

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 '<em>'.implode(" ",$result).'</em>';
}
七婞 2024-11-23 11:15:27

如果您希望脚本不忽略句号、逗号和其他标点符号,那么您应该采用这种方法。

 function getExcerpt($text)
{
   $my_excerptLength = 100; 
   $my_array = explode(" ",$text);
   $value = implode(" ",array_slice($my_array,0,$my_excerptLength));
   return 

}

注:这只是一个例子,希望对您有帮助。如果对您有帮助,别忘了投票。

If you want that your script should not ignore the period and comma and other punctuation symbols then you should adopt this approach.

 function getExcerpt($text)
{
   $my_excerptLength = 100; 
   $my_array = explode(" ",$text);
   $value = implode(" ",array_slice($my_array,0,$my_excerptLength));
   return 

}

Note : This is just an example.Hope it will help you.Don't forget to vote if it help you.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文