Truncate Text Preserving HTML Tags With PHP
Join the DZone community and get the full member experience.
Join For FreeTruncate/limit text preserving the HTML tags (the code auto-closes the tags).
Example
echo String::truncate('jonas', 3, '...'); //jo<...
echo String::truncate('jonas', 3, '...', true); //jon...
echo String::truncate('jonas', 3, '...', true, false); //jon...
Code
//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com
class String{
public static function truncate($s, $l, $e = '...', $isHTML = false){
$i = 0;
$tags = array();
if($isHTML){
preg_match_all('/<[^>]+>([^<]*)/', $s, $m, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
foreach($m as $o){
if($o[0][1] - $i >= $l)
break;
$t = substr(strtok($o[0][0], " \t\n\r\0\x0B>"), 1);
if($t[0] != '/')
$tags[] = $t;
elseif(end($tags) == substr($t, 1))
array_pop($tags);
$i += $o[1][1] - $o[0][1];
}
}
return substr($s, 0, $l = min(strlen($s), $l + $i)) . (count($tags = array_reverse($tags)) ? '' . implode('>', $tags) . '>' : '') . (strlen($s) > $l ? $e : '');
}
}
PHP
HTML
Truncate (SQL)
Opinions expressed by DZone contributors are their own.
Comments