I thought I’d share a code snippet that I wrote this morning to truncate long news titles that appear on the homepage of WNET’s worldfocus.org site. The code truncates on the nearest word boundary if the text is longer than the requested maximum length.
function truncate($text, $max_length = -1, $more = "...") { if (($max_length > -1) && (strlen($text) > $max_length)) { $more_length = strlen($more); $text_length = $max_length - $more_length; while ( ($text_length > 0) && (substr($text, $text_length - 1, 1) != " ")) $text_length--; if ($text_length <= 0) $text_length = $max_length - $more_length; $text = substr($text, 0, $text_length) . htmlspecialchars($more); } return $text; }
Example usage:
truncate("this is a very long sentence", 15)
Update:
Based on a comment on the PHP subreddit pointing me to the Smarty truncation function along with frans comment below I’ve tightend up the function to:
function truncate2($text, $max_length = -1, $more = "...") { if (($max_length > -1) && (strlen($text) > $max_length)) { $max_length -= min($max_length, strlen($more)); // from Smarty code $space_pos = strrpos(substr($text, 0, $max_length), " "); $text = substr($text, 0, $space_pos === false ? $max_length : $space_pos) . htmlspecialchars($more); } return $text; }
Leave a Reply
Copyright © 2012 Tierra Innovation, Inc.
|
RSS | Client Login
December 16th, 2008 at 7:05 pm
Instead of
while ( ($text_length > 0)
&& (substr($text, $text_length – 1, 1) != ” “))
$text_length–;
if ($text_length <= 0)
you could say
$text_length = strrpos($text, ‘ ‘, $text_length);
if ($text_length === false)
December 16th, 2008 at 7:16 pm
frans: Cool. I wasn’t aware of the offset parameter was available in strrpos().
December 16th, 2008 at 7:51 pm
Just double-checked strrpos() and the offset is where it stops scanning for characters and not where is starts so using it would find the first space after the requested text length and not the one preceeding it. I have updated the code to use strrpos in a different way to get rid of the loop.
December 16th, 2008 at 8:30 pm
Ummm – http://www.reddit.com/r/PHP/comments/7juw9/code_snippet_trimming_text_on_word_boundaries_in/c06v3xr
December 17th, 2008 at 1:15 am
$text = wordwrap($text, $max_length, “\n”);
$text = strstr($text, “\n”, true);
// wordwrap will insert “\n” at $max_length intervals conforming to word boundaries
// strstr as of 5.3.0 will return $text upto the first “\n”