Tips & Tutorial

PHP: Keep HTML Tags Paired

Oleh takien

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:

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;
}

Usage/Example:

$fullcontent = '<p>This is my first post blah blah blah...</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>

Feedback and comment are welcome. Thanks

Tulisan ini sudah berumur: 16 tahun 9 bulan 24 hari. Informasi di dalamnya mungkin sudah tidak relevan, tapi nilai historisnya sangat berharga, terutama bagi saya sebagai penulisnya.

Tag Terkait: