gherardobertini / truncate-html
Truncate HTML strings keeping valid tags without truncating words
Installs: 450
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 1
Forks: 0
Open Issues: 0
pkg:composer/gherardobertini/truncate-html
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-12-04 13:52:45 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$startto 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.