PHP limit the number of words from a string

时间:2017-04-06 17:06:12

标签: php

I have been using a function I found here at StackOverflow from another answer elsewhere. While the function helps me and does what I want, sometimes the result isn't accurate. (credits to the author I don't remember the link)

function truncate ($str, $length) {
    if (strlen($str) > $length) {
        $str = substr($str, 0, $length+1);
        $pos = strrpos($str, ' ');
        $str = substr($str, 0, ($pos > 0)? $pos : $length);
    }
    return $str;
}

That is the function I am using. However, sometimes it cuts off after a period which the paragraph ends up making no sense. For example, it ends like this:

It's Always Sunny in Philadelphia is an American comedy series about four friends in their late 20s with clear sociopathic tendencies who run an unsuccessful Irish bar, "Paddy's Pub," in South Philadelphia. The

I would like to end like this:

It's Always Sunny in Philadelphia is an American comedy series about four friends in their late 20s with clear sociopathic tendencies who run an unsuccessful Irish bar, "Paddy's Pub," in South Philadelphia.

I want it to cut after the closest period; regardless I set it to cut after 200 words. Even if it ends up cutting at the 190th word.

0 个答案:

没有答案