Page 1 of 1

limiting a strings word count

Posted: Tue Mar 29, 2011 8:14 am
by ediblecastle
hello there. I'm currently trying to edit a wordpress theme's php function which is a bit tricky for me as I don't know php.

was wondering if some nice fellow/fellowess could help?

The function at the moment counts the string's character length. If it's over a certain number- it displays a certain number of characters from the string and adds "..." to it.

here's what I have so far:

function bm_better_excerpt($length, $ellipsis) {
$text = get_the_content();
$text = strip_tags($text);
if($length > 20){
$text = substr($text, 0, 20);
$text = $text.$ellipsis;
return $text;
}
return $text;
}

apologies if I'm missing any needed info. I'm not really writing php code. I'm more... editing(messing up) what's already there

But, to the point- what I'd really like to do is have it count the number of words in the string and then if it's too high- output a certain amount of words + the ellipsis.

Could someone assist me?

Thanks,
-Will

Re: limiting a strings word count

Posted: Tue Mar 29, 2011 9:47 am
by Peter Kelly
I have a function back at home that does exactly what you want, I created it a few years ago. I will edit this post in a couple hours when I get home with the code.

Re: limiting a strings word count

Posted: Tue Mar 29, 2011 2:53 pm
by AbraCadaver
Quick and dirty:

Code: Select all

function bm_better_excerpt($text, $length, $ellipsis) {
    $words = explode(' ', $text, $length);
    array_pop($words);
    return implode(' ', $words) . $ellipsis;
}
or

Code: Select all

function bm_better_excerpt($text, $length, $ellipsis) {
    $words = explode(' ', $text, $length);
    return implode(' ', array_slice($words, 0, $length-1)) . $ellipsis;
}

Re: limiting a strings word count

Posted: Tue Mar 29, 2011 4:26 pm
by John Cartwright
This was a solution that I wrote over on another forum, which was based on a snipplet originally created by feyd. It's not exactly per your requirements, but I would suggest using character limits over word limits, since you cannot control the sum of the length of all your words otherwise.

Code: Select all

function get_cat_desc($description, $max_length = 50) {
    $the_description = strip_tags($description);
    if(strlen($the_description) > $max_length && preg_match('#^\s*(.{'. $max_length .',}?)[,.\s]+.*$#s', $the_description, $matches)) {
        return $matches[1] .'...';
    } else {
        return $the_description;
    }
}
It basically limits the text to a certain number of characters, but will not stop on a period, comma, or a space to avoid weird looking endings, i.e.,

",...", or "...."