Convert substr filter from character count to word count

五迷三道 提交于 2019-12-20 02:15:37

问题


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

回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/6416411/convert-substr-filter-from-character-count-to-word-count

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!