The name of this function makes it pretty self-explanatory. One particularly useful thing about the function is that it allows you to either trim it at the end and add an ellipsis (…) or insert HTML page breaks (<br />). Very useful.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/*------------------------------------------------------------------------------------------------*\
  Function:    trim_long_string
  Description: helper function to help manage long strings. This function either adds an ellipsis
                   or inserts a <br /> at the position specified, and returns the result.  
  Parameters: $str    - the string to examine
                   $length - the max length of the string / place to insert <br />
                   $flag   - "ellipsis" / "page_break"
\*------------------------------------------------------------------------------------------------*/

function trim_long_string($str, $length, $flag = "ellipsis")
{
  $new_string = "";
  if (strlen($str) < $length)
    $new_string = $str;
  else
  {
    if ($flag == "ellipsis")
      $new_string = substr($str, 0, $length) . "...";
    else
    {
      $parts = str_split($str, $length);
      $new_string = join("<br />", $parts);
    }
  }

  return $new_string;
}