I have a variable that is formatted with random HTML code. I call him {$text}and I truncate him.
Value, for example:
<div>Lorem <i>ipsum <b>dolor <span>sit </span>amet</b>, con</i> elit.</div>
If I truncate the text first ~ 30 letters, I get this:
<div>Lorem <i>ipsum <b>dolor <span>sit
The problem is that I cannot close the elements. So, I need a script that checks the elements <*>in the code (where * can be anything), and if it does not have a close tag, close it.
Please help me with this. Thank.
Solution for hours and 4 polls @stackoverflow:
PHP:
...
function closetags($content) {
preg_match_all('#<(?!meta|img|br|hr|input\b)\b([a-z]+)(?: .*)?(?<![/|/ ])>#iU', $content, $result);
$openedtags = $result[1];
preg_match_all('#</([a-z]+)>#iU', $content, $result);
$closedtags = $result[1];
$len_opened = count($openedtags);
if (count($closedtags) == $len_opened) {
return $content;
}
$openedtags = array_reverse($openedtags);
for ($i=0; $i < $len_opened; $i++) {
if (!in_array($openedtags[$i], $closedtags)) {
$content .= '</'.$openedtags[$i].'>';
} else {
unset($closedtags[array_search($openedtags[$i], $closedtags)]);
}
}
return $content;
}
...
TPL:
{$pages[j].text|truncate:300|@closetags}
source
share