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
Release: 2024-11-13 00:04:01
Original
1031 people have browsed it

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...
}
Copy after login

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>");
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template