Home >Backend Development >PHP Tutorial >How to Truncate HTML Text while Preserving Tag Structure?

How to Truncate HTML Text while Preserving Tag Structure?

Linda Hamilton
Linda HamiltonOriginal
2024-11-13 00:04:011033browse

How to Truncate HTML Text while Preserving Tag Structure?

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]+)[^>]*>|&amp;#?[a-zA-Z0-9]+;|[\x80-\xFF][\x80-\xBF]*}'
        : '{</?([a-z]+)[^>]*>|&amp;#?[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>&amp;lt;Hello&amp;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>&amp;#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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn