gherardobertini/truncate-html

Truncate HTML strings keeping valid tags without truncating words

dev-main 2025-04-04 12:31 UTC

This package is auto-updated.

Last update: 2025-07-04 12:55:59 UTC


README

A lightweight PHP library to safely truncate HTML strings without breaking tags or cutting words.

๐Ÿ“ฆ Installation

Install via Composer:

composer require gherardobertini/truncate-html

๐Ÿš€ Usage

use Gherardobertini\TruncateHtml\TruncateHtml;

$html = "<p>Hello this is a test</p>";

echo TruncateHtml::truncate($html, 0, 10);
// Output: <p>Hello this</p>

echo TruncateHtml::truncate($html, 10);
// Output: <p>is a test</p>

๐Ÿ”ง Method Signature

public static function truncate(string $html, int $start = 0, ?int $length = null): string
  • $start โ€” The character offset where to begin (default is 0).
  • $length โ€” The number of characters to include (optional). If null, returns everything from $start to the end.
  • Words are never cut in half.
  • Open tags are properly closed to maintain valid HTML.

โœ… Example

$html = "<p>Hello this is a test</p>";

TruncateHtml::truncate($html, 0, 10);  // <p>Hello this</p>
TruncateHtml::truncate($html, 10);     // <p>is a test</p>

๐Ÿงช Running Tests

Install dependencies and run PHPUnit:

composer install
vendor/bin/phpunit

๐Ÿ“„ License

MIT License โ€“ see the LICENSE file for details.