Truncating Text Containing HTML with Tag Preservation
Challenge
Truncating text with embedded HTML tags often leads to incomplete or incorrectly closed tags. How can we truncate the text effectively while preserving the HTML structure?
Solution: Tag-Aware Truncation
To preserve the HTML structure, we need to keep track of and manage open and closed tags. Here's a PHP implementation:
function printTruncated($maxLength, $html, $isUtf8 = true) { $printedLength = 0; $position = 0; $tags = []; $re = $isUtf8 ? '{</?([a-z]+)[^>]*>|&#?[a-zA-Z0-9]+;|[\x80-\xFF][\x80-\xBF]*}' : '{</?([a-z]+)[^>]*>|&#?[a-zA-Z0-9]+;}'; while ($printedLength < $maxLength && preg_match($re, $html, $match, PREG_OFFSET_CAPTURE, $position)) { list($tag, $tagPosition) = $match[0]; $str = substr($html, $position, $tagPosition - $position); # More code... # Continue after the tag. $position = $tagPosition + strlen($tag); } # More code... }
Example Usage
printTruncated(10, '<b>&lt;Hello&gt;</b> <img src="world.png" alt="" /> world!'); printTruncated(10, '<table><tr><td>Heck, </td><td>throw</td></tr><tr><td>in a</td><td>table</td></tr></table>'); printTruncated(10, "<em><b>Hello</b>&#20;w\xC3\xB8rld!</em>");
Note:
The function assumes UTF-8 encoding. For other encodings, use mb_convert_encoding to convert to UTF-8 before truncation.
The above is the detailed content of How to Truncate HTML Text while Preserving Tag Structure?. For more information, please follow other related articles on the PHP Chinese website!