Well, I see I should read thoroughly what people post before writting anything
First of all, some 'problems' and code I have posted was copied from Firebug console, which was messing things with these unclosed tags. Sorry, my bad.
Now, with such great code Ryan posted I could move ahead but still couldn't stand one thing, which was messing my site. What if it will cut output in the middle of tag definition (for example long IMG or A tags) ? So I've fixed it:
?php
if (!isset($options)) $options = 1000;
$charcount = $options;
$output = $input;
$pad = " .....";
$addpad = false;
if(false !== ($breakpoint = strpos($output, " ", $charcount))) {
if ($breakpoint < strlen($output) - 1) {
$output = substr($output, 0, $breakpoint);
$addpad = true;
}
}
$opened = array();
if(preg_match_all("/<(\/?[a-z]+)>/i", $output, $matches)) {
foreach($matches[1] as $tag) {
if(preg_match("/^[a-z]+$/i", $tag, $regs)) {
if(strtolower($regs[0]) != 'br' || strtolower($regs[0]) != 'hr') $opened[] = $regs[0];
} elseif(preg_match("/^\/([a-z]+)$/i", $tag, $regs)) {
unset($opened[array_pop(array_keys($opened, $regs[1]))]);
}
}
}
/* checking for unfinished tag at the end */
$loab = strrpos($output, "<");
if (!$loab) {$loab = -1;}
$lcab = strrpos($output, ">");
if (!$lcab) {$lcab = -1;}
/*if we found that there is unfinished tag, let's trim output, removing this tag */
if ($loab > $lcab) {$output = substr($output, 0, $loab);}
/* now we can add pad */
if ($addpad) {$output .= $pad;}
/* the rest - closing opened tags */
if($opened) {
$tagstoclose = array_reverse($opened);
foreach($tagstoclose as $tag) $output .= "</$tag>";
}
return $output;
It works well on my site and I feel like damn god of coding now
. I have not programmed anything for years. Because of this and my zero experience with regular expressions this code may be non-godlike
.
Thanks everyone for helping !