PHPackages                             zjkiza/truncate-html - 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. zjkiza/truncate-html

ActivePhp-package

zjkiza/truncate-html
====================

A flexible HTML truncation service that safely truncates HTML content without breaking the tag structure. Enable different ways of measuring length by bytes or by characters.

v0.6.2(3mo ago)35MITPHPPHP &gt;=8.1

Since Nov 17Pushed 3mo agoCompare

[ Source](https://github.com/zjkiza/truncate-html)[ Packagist](https://packagist.org/packages/zjkiza/truncate-html)[ RSS](/packages/zjkiza-truncate-html/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (4)Dependencies (8)Versions (5)Used By (0)

PHP package: Truncate Html
==========================

[](#php-package-truncate-html)

A flexible PHP service to safely truncate HTML content **without breaking tag structure**. Provides multiple truncation strategies—by bytes or by characters—making it ideal for displaying safe previews, snippets or social meta content.

---

**Flexible PHP service for safely shortening HTML content without breaking tag structure. It supports different truncation strategies: byte-wise or character-wise.**
---------------------------------------------------------------------------------------------------------------------------------------------------------------------

[](#flexible-php-service-for-safely-shortening-html-content-without-breaking-tag-structure-it-supports-different-truncation-strategies-byte-wise-or-character-wise)

Features
--------

[](#features)

- ✔️ Preserves valid HTML – no broken or unclosed tags
- ✔️ Supports truncating by bytes (for precise control, ex. for database or API)
- ✔️ Supports truncating by characters (multibyte safe)
- ✔️ Custom void tags
- ✔️ Simple API, PSR-4 autoload compatible
- ✔️ PHP 8.1+, mbstring required

Installation
------------

[](#installation)

Install via [Composer](https://getcomposer.org/):

```
composer require zjkiza/truncate-html
```

> You need PHP 8.1+ and ext-mbstring enabled.

---

Basic Usage
-----------

[](#basic-usage)

Truncate HTML to a byte or character limit, safely:

```
use ZJKiza\TruncateHtml\TruncateHtml;
use ZJKiza\TruncateHtml\Enum\Strategy;

$html = 'Some rich HTML ...';

$truncate = new TruncateHtml();

// --- Byte limit (precise control, for APIs/db):
$resultByte = $truncate->execute($html, Strategy::Bytes, 100);

// --- Character limit (supports multibyte chars!):
$resultChar = $truncate->execute($html, Strategy::Characters, 80);
```

After truncation, the string remains a valid HTML fragment.

---

### Output Examples

[](#output-examples)

For byte/char limits, HTML tags remain valid:

- Input: ```
    Lorem ipsum ...
    ```
- Truncated output (limit adjusted): ```
    Lorem ipsum ...
    ```
- Even if the cut is inside a tag, all tags are properly closed!

---

Truncation Strategies
---------------------

[](#truncation-strategies)

- **Strategy::Bytes**: Cuts by bytes. Use when you need strict byte limits (DB, APIs, etc).
- **Strategy::Characters**: Cuts by characters using mbstring (multi-byte safe, e.g., for Unicode strings).

**Default encoding is UTF-8**, but can be overridden.

Usage in Frameworks / (example: Laravel, Symfony)
-------------------------------------------------

[](#usage-in-frameworks--example-laravel-symfony)

> Register TruncateHtml as a service for injection.

### Symfony (services.yaml)

[](#symfony-servicesyaml)

```
services:
  ZJKiza\TruncateHtml\Contract\TruncateHtmlInterface:
      class: ZJKiza\TruncateHtml\TruncateHtml
```

Then simply inject as needed in your services/controllers.

### Laravel (in AppServiceProvider)

[](#laravel-in-appserviceprovider)

```
use ZJKiza\TruncateHtml\Contract\TruncateHtmlInterface;
use ZJKiza\TruncateHtml\TruncateHtml;

public function register()
{
        $this->app->bind(TruncateHtmlInterface::class, function () {
            return TruncateHtml::create();
}
```

And type-hint `TruncateHtmlInterface` in your controllers/services.

---

Advanced: Custom void/self-closing tags
---------------------------------------

[](#advanced-custom-voidself-closing-tags)

If you need to support additional self-closing/void tags, pass them as an array when constructing:

```
$truncate = new TruncateHtml(['customtag', ... ]);
```

Testing
-------

[](#testing)

To run tests:

```
composer install
vendor/bin/phpunit
```

---

License
-------

[](#license)

MIT License (c) 2025 Zoran Jankovic

---

Author &amp; Contact
--------------------

[](#author--contact)

- Zoran Jankovic

Contributions
-------------

[](#contributions)

Pull requests and suggestions are welcome! See `tests/Functionality/TruncateHtmlTest.php` for examples.

---

Changelog
---------

[](#changelog)

See [CHANGELOG.md](./CHANGELOG.md)

###  Health Score

35

—

LowBetter than 80% of packages

Maintenance82

Actively maintained with recent releases

Popularity8

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity37

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

Every ~30 days

Total

4

Last Release

91d ago

PHP version history (2 changes)v0.5PHP &gt;=8.0

v0.6PHP &gt;=8.1

### Community

Maintainers

![](https://www.gravatar.com/avatar/5ff452349a91001f15f3a1d5ddf5a3a7382218f9222bc3fbfdd005d6c5f0473c?d=identicon)[zjkiza](/maintainers/zjkiza)

---

Top Contributors

[![zjkiza](https://avatars.githubusercontent.com/u/31966449?v=4)](https://github.com/zjkiza "zjkiza (11 commits)")

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan, Psalm, Rector

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/zjkiza-truncate-html/health.svg)

```
[![Health](https://phpackages.com/badges/zjkiza-truncate-html/health.svg)](https://phpackages.com/packages/zjkiza-truncate-html)
```

PHPackages © 2026

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