I like the idea of the $remove_spaces, that's a good idea.
Made a little expansion on it and included SheenBRs idea:
PHP Code:
<?php
function truncate( $str, $allowed_length=10, $remove_spaces=false, $after_str="" )
{
/*
$str - the string to truncate
$allowed_length - the amount of characters to limit to
$remove_spaces - use trim() to remove white-space
$after_str - another string to appear after the truncation, could be '...' if you like, so you could have a snippet of a story with "..." at the end
*/
$str = ( $remove_spaces == true ) ? trim( $str ) : $str;
$return = substr( $str, 0, $allowed_length );
if ( !empty( $after_str ) ) $return .= $after_str;
return $return;
}
echo truncate( "Mark Eriksson is the best person ever!" ); //output: Mark Eriks
echo truncate( "Mark Eriksson is the best person ever!", 25 ); //output: Mark Eriksson is the best
echo truncate( "Mark Eriksson is the best person ever!", 25, false, "..." ); //output: Mark Eriksson is the best...
echo truncate( " Mark Eriksson is the best person ever! ", 20, true, "..." ); //output: Mark Eriksson is the...
?>