Tierra Innovation

Tierra Lab

Code Snippet: Trimming text on word boundaries in PHP

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;
}

Bookmark and Share

5 Responses to “Code Snippet: Trimming text on word boundaries in PHP”

  1. frans Says:

    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)

  2. Doug Says:

    frans: Cool. I wasn’t aware of the offset parameter was available in strrpos().

  3. Doug Says:

    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.

  4. Harry Fuecks Says:

    Ummm – http://www.reddit.com/r/PHP/comments/7juw9/code_snippet_trimming_text_on_word_boundaries_in/c06v3xr

  5. FG Says:

    $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”


Leave a Reply

Copyright © 2012 Tierra Innovation, Inc.