After applying substr to a string that contains HTML tags, usually I found that the result is broken because the closing tags are truncated.
To prevent this, I have made a function that keep the closing tags remains and will not break the appearance of my website.
Here is the function:
HTML Pair Tags
<?php</p>
function pair_tag($string) {
$tags = Array('em','i','b','strong','div','span','p');
//array of tags we will keep paired, you may add another
foreach($tags as $tag) {
$opentag = substr_count($string, '<'.$tag);
// I don't put > in the opentag in case they may have an attribute
$closetag = substr_count($string, '</'.$tag.'>');
if($opentag !== $closetag) {
$return .= str_repeat('</'.$tag.'>', ($opentag-$closetag));
}
}
return $return;
}
<p>?>
Usage/Example:
Example
<?php</p>
$excerpt = substr($string, 0, 20); //only display first 20 character
$excerpt .= pair_tag($excerpt); // this will count any unclosed tags then close it.
echo $excerpt; // returns <p>This is my first pos</p>
<p>?>
Feedback and comment are welcome. Thanks
