【问题标题】:Convert substr filter from character count to word count将 substr 过滤器从字符数转换为字数
【发布时间】:2011-09-18 23:21:44
【问题描述】:

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

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

【问题讨论】:

    标签: php substr


    【解决方案1】:

    使用str_word_count

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

    所以,要返回一个 sn-p 文本的前 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>';
    }
    

    【讨论】:

    • PHP 有一个内置函数可以处理所有看起来的事情。
    • 很酷,但是当我用 str_word_count 替换 substr 时,它只返回字数。我错过了什么?
    • 试试上面的。请注意,这不会保留标点符号(因为它只会在单词之间添加空格)。另一种解决方案是使用正则表达式。
    【解决方案2】:

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

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

    注意:这只是一个例子。希望对您有所帮助。如果对您有帮助,请不要忘记投票。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-05
      • 1970-01-01
      • 2014-05-11
      • 2023-01-09
      • 1970-01-01
      • 2022-08-22
      相关资源
      最近更新 更多