WordPress has built in functions to do this. The only problem is that it assumes, that all your excerpts should have the same max-length.
If this assumption is OK, all you have to do is to define this maximal value.
You can do this with this filter (put it into functions.php
file):
function my_excerpt_length( $length ) {
return 40; // put new excerpt length in here
}
add_filter( 'excerpt_length', 'my_excerpt_length' );
Then in your template file you just have to do this:
setup_postdata( $post );
the_excerpt();
If you need to use different excerpt lengths in different places on your site, then you can use something like this (add this function to functions.php):
function my_trim_excerpt($text = '', $excerpt_length =0) {
if ( !$excerpt_length )
$excerpt_length = apply_filters('excerpt_length', 55);
$raw_excerpt = $text;
$text = strip_shortcodes( $text );
$text = apply_filters('the_content', $text);
$text = str_replace(']]>', ']]>', $text);
$excerpt_length = apply_filters('excerpt_length', 55);
$excerpt_more = apply_filters('excerpt_more', ' ' . '[...]');
$text = wp_trim_words( $text, $excerpt_length, $excerpt_more );
return apply_filters('get_the_excerpt', apply_filters('wp_trim_excerpt', $text, $raw_excerpt));
}
Then use it like this:
echo apply_filters('the_excerpt', my_trim_excerpt($post->post_content, 40)); // 40 is the excerpt length