gherardobertini / truncate-html
Truncate HTML strings keeping valid tags without truncating words
dev-main
2025-04-04 12:31 UTC
Requires
- php: >=8.2
- ext-ctype: *
- ext-dom: *
- ext-iconv: *
- ext-libxml: *
- ext-mbstring: *
Requires (Dev)
- phpunit/phpunit: ^11.5
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 is0
).$length
โ The number of characters to include (optional). Ifnull
, 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.