PHPackages                             md-php/html-truncation - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. md-php/html-truncation

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

md-php/html-truncation
======================

Provides contract and implementation to truncate HTML code

1.0.0(2mo ago)025↓100%MITPHPPHP ^7.1 || ^8.0CI passing

Since Mar 29Pushed 1mo agoCompare

[ Source](https://github.com/md-php/html-truncation)[ Packagist](https://packagist.org/packages/md-php/html-truncation)[ Docs](https://development.md.land/php/md.html.truncation)[ RSS](/packages/md-php-html-truncation/feed)WikiDiscussions master Synced 1w ago

READMEChangelogDependencies (2)Versions (2)Used By (0)

md-php/html-truncation
======================

[](#md-phphtml-truncation)

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

Powered on top of [libxml](https://www.php.net/manual/en/book.libxml.php), [dom](https://www.php.net/manual/en/book.dom.php) and [mbstring](https://www.php.net/manual/en/book.mbstring.php)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)

[![Architecture overview class diagram](docs/_static/architecture-overview.class-diagram.svg)](docs/_static/architecture-overview.class-diagram.svg)

Features
--------

[](#features)

- **Modern.** SOLID &amp; PSR compatible / linted with strict PHPStan and Psalm
- **Fast.** Recursion-free algorithm
- **Memory-efficient.** Supports huge documents with nesting up to 100,000 elements (optionally)
- **Fresh.** Created in 2026, supports latest PHP versions (7.1+ and 8.0+)

Install
-------

[](#install)

```
composer require md-php/html-truncation
```

Usage
-----

[](#usage)

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

Read documentation for more examples.

### Integration with Twig

[](#integration-with-twig)

Take a look for a [md-php/bridge-twig-html-truncation](https://github.com/md-php/bridge-twig-html-truncation)component that provides additional Twig filter and function to truncate HTML code, like:

```
{{ "some long html code"|truncate_html_with_text_length(4) }}
```

or

```
{{ "some long markdown text"|markdown|raw|truncate_html_with_text_length(8, ';;;') }}
```

[Documentation](docs/index.md)
------------------------------

[](#documentation)

Read documentation with examples:

Development
-----------

[](#development)

Initial setup:

```
cp .env.dist .env  # ... change `.env` for your needs
cp phpunit.php71.xml.dist phpunit.xml  # ... choose either 71 or 80 for your needs
```

Run checks (Psalm + PHPStan + PHPUnit):

```
docker compose run --build --remove-orphans --entrypoint='/usr/src/app/vendor/bin/deptrac analyse --config-file=deptrac.yaml' run-deptrac

for PHP_VERSION in '71' '80' '85'; do
  export PHP_VERSION="$PHP_VERSION"
  docker compose run -v "$PWD/vendor${PHP_VERSION}:/app/vendor" --build --remove-orphans --env-from-file .env -e XDEBUG_MODE=coverage --entrypoint="bash -c 'composer install ; mv composer.lock composer.php$PHP_VERSION.lock'" run-tests
  docker compose run -v "$PWD/vendor${PHP_VERSION}:/app/vendor" --build --remove-orphans --env-from-file .env -e XDEBUG_MODE=coverage --entrypoint="/usr/src/app/vendor/bin/phpunit --configuration /usr/src/app/phpunit.php$(( PHP_VERSION == 85 ? 80 : PHP_VERSION )).xml.dist --coverage-text" run-tests
  docker run -e "PHP_VERSION=$PHP_VERSION" -v "$PWD:/app" -v "$PWD/vendor${PHP_VERSION}:/app/vendor" --rm -it ghcr.io/danog/psalm:latest /composer/vendor/bin/psalm --no-cache
  docker run -e "PHP_VERSION=$PHP_VERSION" -v "$PWD:/app" -v "$PWD/vendor${PHP_VERSION}:/app/vendor" --rm -it ghcr.io/phpstan/phpstan analyse --configuration phpstan.neon
done;
```

Validate files:

```
composer validate --strict
find ./src ./tests -name "*.php" -exec php -l {} \;
```

Comparison with other solutions
-------------------------------

[](#comparison-with-other-solutions)

- **md-php/html-truncation (THIS)**
    - **Method:** libxml ✅
    - **Stars:** N/A
    - **Installs:** N/A
    - **Status:** Last update: 2026-03-25
    - **Features:** [(see features)](#features)
    - **PHP version:** `^7.1` or `^8.0` ✅
- urodoz/truncate-html
    - **Method:** regular expression ❗
    - **Stars:** 21
    - **Installs:** 287,129
    - **Status:**
        Last update: 2014-05-25 ❗
        Abandoned (De-facto): No updates, no activity on issues. ❗
    - **PHP version:** `>=5.3` ❗
    - **Cons:**
        - Coupled to Twig component ❗️
- bluetel/twig-truncate-extension
    - **Method:** libxml ✅
    - **Stars:** 11
    - **Installs:** 97,376
    - **Status:**
        Last update: 2016-01-19 ❗
        Abandoned (De-facto): No updates, no activity on issues. ❗
    - **PHP version:** `>=5.3` ❗
    - **Cons:**
        - issues in master branch ❗
            - dumps result only as HTML as full document, no fragment support.
        - recursion method ❗
        - Coupled to Twig component ❗
- judev/php-htmltruncator
    - **Method:** libxml ✅
    - **Stars:** 29
    - **Installs:** 271,305
    - **Status:**
        Last update: 2019-11-19 ❗
        Abandoned (no updates, no activity on issues) ❗
    - **PHP version:** `>=5.6` ❗
    - **Cons**
        - One class per file principle violation ❗️
- dzango/TwigTruncateExtension
    - **Method:** regular expression ❗️
    - **Stars:** 13
    - **Installs:** 236,921
    - **Status:**
        Last update: 2017-12-02 ❗️
        Abandoned (no updates, no activity on issues) ❗
    - **PHP version:** `>=5.6` ❗
    - **Pros:**
        - Adjust cut off in the middle of the word ✅
    - **Cons:**
        - One class per file principle violation ❗️
        - Coupled to Twig component ❗️

Roadmap
-------

[](#roadmap)

- add cut off in the middle of the word adjustment
- add feature to truncate text by the words count
- add feature to exclude elements from text truncation
- add benchmarks
- simplify Dockerfile

[Changelog](changelog.md)
-------------------------

[](#changelog)

[License (MIT)](license.md)
---------------------------

[](#license-mit)

###  Health Score

36

—

LowBetter than 79% of packages

Maintenance88

Actively maintained with recent releases

Popularity7

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity38

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

72d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/ee307dc6bfc713606c213571f27ddb1143670b6d94754bb090995f33c8e78b46?d=identicon)[unsektor](/maintainers/unsektor)

---

Top Contributors

[![unsektor](https://avatars.githubusercontent.com/u/529297?v=4)](https://github.com/unsektor "unsektor (2 commits)")

---

Tags

htmlhtml-truncatephpsolid-principlestruncationhtmltruncatetruncation

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/md-php-html-truncation/health.svg)

```
[![Health](https://phpackages.com/badges/md-php-html-truncation/health.svg)](https://phpackages.com/packages/md-php-html-truncation)
```

###  Alternatives

[civicrm/civicrm-core

Open source constituent relationship management for non-profits, NGOs and advocacy organizations.

744284.3k34](/packages/civicrm-civicrm-core)[spatie/laravel-html

A fluent html builder

8307.1M91](/packages/spatie-laravel-html)[caxy/php-htmldiff

A library for comparing two HTML files/snippets and highlighting the differences using simple HTML.

21421.8M20](/packages/caxy-php-htmldiff)[yajra/laravel-datatables-html

Laravel DataTables HTML builder plugin

28410.1M49](/packages/yajra-laravel-datatables-html)[tinymce/tinymce

Web based JavaScript HTML WYSIWYG editor control.

1697.9M118](/packages/tinymce-tinymce)[voku/html-min

HTML Compressor and Minifier

1884.9M57](/packages/voku-html-min)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
