Skip to content

md-php/html-truncation

md-php/html-truncation is a PHP component that provides contract and implementation to truncate HTML code.

Powered on top of libxml, dom and mbstring builtin PHP extensions.

Text truncation is the process of shortening a piece of text by cutting it off after a certain length, typically adding an ellipsis ... or another indicator to show that the content has been clipped.

It's useful to create snippets showing only relevant context around a keyword and especially useful to limit content of items in list, for example: generic entry content in admin list, blog articles content and so on.

Architecture overview

Architecture overview class diagram

Install

composer require md-php/html-truncation

Usage

Basic usage example:

$truncateHtml = new \MD\HTML\Action\Truncate(allowHugeDocument: false);
$truncateHtml->withTextLength(
    html: '<p>some very long html code</p>',
    maxLength: 10,
    ending: '...'
);  # ... will return: '<p>some very ...</p>'

Advanced example:

<?php

declare(strict_types=1);

use MD\HTML\Action\TruncateInterface;
use MD\HTML\Action\Truncate;
use MD\HTML\Exception\TruncateException;

class Controller
{
    public function __construct(
        private readonly TruncateInterface $truncateHtml
    ) {}

    public function act(): string 
    {
        $code = '<p>some very long html code</p>'; 
        try {
            return $this->truncateHtml->withTextLength(html: $code, maxLength: 10, ending: '...');
        } catch (TruncateException $exception) {  // ... Should never happen
            throw $exception;
            // return '';
        }
    }
}

// Usage
$truncateHtml = new Truncate(allowHugeDocument: false);
$controller = new Controller(truncateHtml: $truncateHtml);
print($controller->act());  // will print: '<p>some very ...</p>

Integration with Twig

Take a look for a md-php/bridge-twig-html-truncation component that provides additional Twig filter and function to truncate HTML code.