Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Truncate Html Laravel Package

urodoz/truncate-html

urodoz/truncate-html is a lightweight PHP library for safely truncating HTML strings to a chosen length without breaking tags. It preserves valid markup, supports custom ellipsis and encoding, and is ideal for generating clean excerpts from rich text in Laravel or any PHP project.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture fit

  • Single-responsibility utility: converts an HTML string into a length-bounded HTML string with tags preserved and unbalanced tags closed. It belongs in the presentation/rendering layer (Blade helpers, excerpt builders, feed/meta generators), not in domain logic.
  • No persistence, no I/O, no configuration surface beyond truncation length/ellipsis/word-boundary flags. That makes it trivially replaceable, which is the main architectural argument in its favor — and the main reason not to let it leak into many call sites.
  • It does not sanitize; it only shortens. It must sit downstream of a sanitizer (e.g., HTMLPurifier, mews/purify) or upstream of a strict output escaper, never as the sole trust boundary.

Integration feasibility

  • Composer-installable, MIT-licensed, PSR-4 autoloaded. Laravel integration is a service provider + facade, so on Laravel 5.5+ it is auto-discovered; older or non-Laravel hosts need manual provider/alias registration or direct class instantiation.
  • Feasibility is gated entirely on composer.json constraints. At 21 stars and effectively no release cadence, expect a php require in the 5.4–7.x range. Verify on the target runtime (PHP 8.1/8.2/8.3) before committing; a hard constraint failure means a fork or a rewrite, and a rewrite of this algorithm is roughly a day of work.
  • The truncation algorithm is regex/DOMDocument-based and therefore deterministic and easy to golden-test, which lowers integration risk considerably.

Technical risk

  • Abandonment risk (high): 21 stars, 0 dependents, single maintainer, no visible CI or test suite. Treat this as unmaintained code you are adopting, not a dependency you are consuming.
  • Correctness risk (medium): HTML truncation has sharp edges — splitting UTF-8 multibyte characters, splitting &amp;-style entities mid-sequence, truncating inside <script>/<style>, closing void elements incorrectly, and mishandling nested or malformed input from user-generated content.
  • Security risk (low but non-zero): truncation can move a closing tag boundary and change how a browser reparses a fragment. Output must still pass through a sanitizer; do not rely on this package for safety.
  • Supply-chain risk (low): tiny dependency tree, MIT, no install scripts — but also no security-response channel.
  • Opportunity signal is weak (39/100 score, 1.045 composite): nothing here suggests ecosystem momentum you would be buying into.

Key questions

  1. Which PHP and Laravel versions are actually supported, and does the package install cleanly on our target runtime?
  2. Is truncation character-based, word-based, or both — and does it guarantee well-formed output for arbitrarily malformed input?
  3. How does it handle UTF-8, HTML entities, void elements, and <script>/<style> content?
  4. What is the performance profile on 50 KB–500 KB documents, and is it safe to call per row in a listing loop?
  5. Do we have a sanitizer in the pipeline that runs after truncation?
  6. Is the maintainer responsive, and what is the realistic cost of forking and owning this outright?

Integration Approach

Stack fit

  • Best fit: Laravel monolith or modular monolith rendering Blade templates, where excerpts are needed for index pages, RSS/Atom summaries, Open Graph descriptions, search-result snippets, and notification/email previews.
  • Poor fit: API-only services with no HTML output, or pipelines that must truncate at scale in batch (prefer a queue job with a cached result).
  • It is a leaf dependency: it should appear in exactly one adapter class, not in controllers, models, or Blade templates directly.

Migration path

  1. Spike (½ day): install in a scratch branch, run a fixture corpus of real production HTML (user comments, CMS articles, pasted email bodies, malformed markup) through it, and diff output against the current behavior.
  2. Adapter: define an internal HtmlTruncator interface with truncate(string $html, int $length, array $options): string. Implement it with this package. All call sites depend on the interface.
  3. Fallback implementation: a DomDocument-based implementation (load with LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD, walk text nodes to the budget, serialize) behind the same interface. This costs little and converts an abandonment risk into a config flag.
  4. Fork option: if PHP 8 support is missing, vendor the class into app/Support with the MIT notice, add tests, and drop the Composer dependency entirely.

Compatibility

  • Pin an exact version in composer.json; do not allow floating ranges on a package with no release discipline.
  • Verify behavior under the project's actual locale/multibyte settings; run the fixture corpus with mb_internal_encoding('UTF-8') and with non-ASCII content, emoji, and CJK text.
  • Confirm the facade alias does not collide with an existing Truncate/Str helper in the app.

Sequencing

  • Week 1: spike + fixture corpus + compatibility verdict (installs cleanly vs. requires fork).
  • Week 2: adapter, interface, fallback implementation, golden-file tests wired into CI.
  • Week 3: shadow-mode comparison in staging (render both old and new output, log diffs), then flip the flag for low-traffic surfaces (RSS, meta descriptions).
  • Week 4: enable for high-visibility surfaces (listing pages, search snippets) after diff review; remove the old code path.

Operational Impact

Maintenance

  • Code surface is small enough to read in an afternoon, so the ongoing cost is near zero. The real cost is ownership: assume no upstream fixes, no PHP-version bumps, no security patches. Budget an hour per major PHP upgrade to re-validate the fork.
  • If forked, add it to the internal "vendored code" register with an owner and a review date.

Support

  • No vendor support, no SLA, no issue-response expectation. Internal escalation must terminate at the owning team, not at the maintainer.
  • Documentation burden is low: one internal README covering the interface, the sanitizer requirement, and the fork provenance.

Scaling

  • CPU-bound string parsing, O(n) in document length. Fine for per-request excerpt generation on documents under ~100 KB.
  • Do not call it per row inside a paginated listing without caching — a 50-row page over 20 KB bodies means 50 parse passes per request. Cache truncated output at write time (a excerpt column or a cache key keyed on content hash + length) rather than truncating at read time.
  • No external services, no network calls, no state — it scales horizontally with the app tier and adds no new failure boundary.

Failure modes

  • Malformed output: unclosed or mis-nested tags after truncation, which browsers may reparse in unexpected ways. Mitigation: sanitize after truncation, and assert well-formedness in tests.
  • Entity/multibyte splitting: a truncated &nbsp; or a halved emoji produces visible garbage. Mitigation: fixture tests; prefer word-boundary truncation.
  • Unsafe content passthrough: truncating inside <script> or preserving event-handler attributes. Mitigation: strip these before truncation, sanitize after.
  • Memory/CPU spikes: very large documents (pasted logs, base64 image payloads in CMS fields) triggering DOM or regex blowups. Mitigation: length-cap input before truncation and fail fast.
  • Silent PHP-version drift: a PHP upgrade breaks the package in a non-obvious way. Mitigation: golden-file tests in CI catch this on the first pipeline run.
  • Behavioral drift vs. legacy: different ellipsis placement or word-breaking changes existing page layouts. Mitigation: the shadow-mode diff phase described above.

Ramp-up

  • Near-zero for any PHP developer: one interface, one class, one config value. Expect ~2 hours to first productive use and ~1 day to full ownership including tests and the fallback implementation.
  • The only non-obvious knowledge to transfer is the pipeline ordering rule: sanitize → truncate → sanitize/escape. Put that in the adapter's docblock, because the next developer will otherwise assume truncation implies safety.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
htinlynn/genius-helper
maco-studios/hephaestus
elmogy/larafast
xeviant/laravel-paystack
gorilladash/laravel-website-sdk
martialbe/flysystem-oss
chondal/3312client
jeroen-g/flickr
opscale-co/nova-genbi
itsjustvita/laravel-retention
tequilarapido/trackit
gregsphotography/site-builder-filament
cabaoctavio/laravel-query-log
gregsphotography/site-builder-components
io-digital/clickatell
snowsoft/laravel-admin
oxygen/auth
relicsoftware/barakah-payment-gateway
tobya/work-with-composer
equipc/laravel-email-validator