/** * Truncate a string that contains HTML tags. Will close all HTML tags as needed. * * Truncates a string to a max. length and optionally adds a filler string, * e.g. '...', to indicate the truncation. * This function is multi-byte string aware. This function is based on a * code snippet by pitje at Snipplr.com. * * NOTE: The truncated string may be shorter or longer than $maxlen characters. * Currently any initial html tags in the truncated string are taken into account. * The $filler string is also taken into account but any html tags that are added * by this function to close open html tags are not. * * @param string $htmltext the text string which contains HTML tags to truncate * @param int $maxlen max. number of characters in the truncated string * @param string $filler optional filler string, e.g. '...' * @param int $endchars number of characters to show after the filler * @return string truncated string * */ function COM_truncateHTML($htmltext, $maxlen, $filler = '', $endchars = 0) { $newlen = $maxlen - MBYTE_strlen($filler); $len = MBYTE_strlen($htmltext); if ($len > $maxlen) { $htmltext = MBYTE_substr($htmltext, 0, $newlen - $endchars); // Strip any mangled tags off the end if (MBYTE_strrpos($htmltext, '<') > MBYTE_strrpos($htmltext, '>')) { $htmltext = MBYTE_substr($htmltext, 0, MBYTE_strrpos($htmltext, '<')); } $htmltext = $htmltext . $filler . MBYTE_substr($htmltext, $len - $endchars, $endchars); // put all opened tags into an array preg_match_all("#<([a-z]+)( .*)?(?!/)>#iU", $htmltext, $result); $openedtags = $result[1]; $openedtags = array_diff($openedtags, array("img", "hr", "br")); $openedtags = array_values($openedtags); // put all closed tags into an array preg_match_all("#</([a-z]+)>#iU", $htmltext, $result); $closedtags = $result[1]; $len_opened = count($openedtags); // all tags are closed if (count($closedtags) == $len_opened) { return $htmltext; } $openedtags = array_reverse($openedtags); // close tags for ($i = 0; $i < $len_opened; $i++) { if (!in_array($openedtags[$i], $closedtags)) { $htmltext .= "</" . $openedtags[$i] . ">"; } else { unset($closedtags[array_search($openedtags[$i], $closedtags)]); } } } return $htmltext; }
/** * Truncate a feed item's text to a given max. length of characters * * @param string $text the item's text * @param int $length max. length * @return string truncated text * */ function SYND_truncateSummary($text, $length) { if ($length == 0) { return ''; } else { $text = stripslashes($text); $text = trim($text); $text = str_replace(array("\r\n", "\r"), "\n", $text); if ($length > 3 && MBYTE_strlen($text) > $length) { $text = MBYTE_substr($text, 0, $length - 3) . '...'; } // Check if we broke an html tag and storytext is now something // like "blah blah <a href= ...". Delete "<*" if so. if (MBYTE_strrpos($text, '<') > MBYTE_strrpos($text, '>')) { $text = MBYTE_substr($text, 0, MBYTE_strrpos($text, '<')) . ' ...'; } return $text; } }