truncate text-strings without cutting words

This is an easy way to truncate strings without cutting words after n characters.

bad one:
Lorem ipsum dolor sit amet, hy…

good one:
Lorem ipsum dolor sit amet, hymenaeos …

$string = "Lorem ipsum dolor sit amet, pellentesque wisi ut congue eget quam.";
$strLength = 30;
echo substr ( $string, 0, strrpos ( $string, ' ', - ( strlen ( $string ) - $strLength ) ) );

Leave a Reply

Your email address will not be published. Required fields are marked *

*

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>