Download the PHP package migears/html-digest without Composer

On this page you can find all versions of the php package migears/html-digest. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package html-digest

migears/html-digest

Version

A lightweight HTML text summary (digest) extractor for PHP 8.1+. It turns HTML into clean plain text and applies smart, multibyte-safe truncation — with zero DOM extension dependencies (built on strip_tags + regex + mbstring).

Designed for the miGears framework philosophy: minimal, dependency-free, readable in minutes.

Background: miGears is the open-source successor of TinyGears, a self-developed PHP framework. It was renamed and open-sourced recently because the name TinyGears is already taken in the open-source community.

Features

Boundaries

In scope

Not in scope (by design)

Installation

Quick Start

Worked example: input → output

To see the real value, compare the original HTML with what each method returns. The sample below is realistic: it contains hidden document chrome (head/title/script/style), a heading, paragraphs with inline formatting, a list, HTML entities,  , an image and a link.

① The original HTML

② toText() — everything invisible is gone

The <head>, <title>, <script>, <style> nodes are dropped entirely; tags are stripped; entities are decoded (&amp; → &, &deg; → °); &nbsp; is collapsed to a space; each block lands on its own line:

No more script, no style, no &amp;, no &nbsp;, no <img> tag noise — just the words a human would read.

③ extract() — summaries at any length, never a cut word

Call Output
extract($html) (default 200) the full clean text from ②
extract($html, 30) A Better Morning: How to...
extract($html, 20) A Better...
extract($html, 10) A...
extract($html, 6, '...', MODE_WORD) A Better Morning: How to Brew...

Watch the word boundary: extract($html, 30) never returns "A Better Morning: How to Co…" — it steps back to the last whitespace, so words are never sliced in half.

④ CJK sample — Chinese is handled too

Call Output
toText() 中文冲泡指南 / 水温、粉量与时长的平衡,是手冲咖啡的关键。 多试几次,你会找到自己的偏好。 / 水温 92°C / 粉量 18 克 (line-separated)
extract($zh, 20) 中文冲泡指南...
extract($zh, 8, '…', MODE_WORD) 中文冲泡指南水温、粉量与时长的平衡,是手冲咖啡的关键。多试几次,你会找到自己的偏好。…

The &nbsp; inside the sentence is normalized to a space, the °C survives, and word mode works on space-less Chinese by counting each CJK character as a token.

Real-world scenarios

Blog / article excerpt

body_html may be a full WYSIWYG blob (headings, images, embedded scripts), but the excerpt stays clean and never mid-word.

SEO meta description

Google typically shows ~155 characters:

Entities and stray markup are already resolved, so the meta tag won't contain raw &amp; or <strong>.

RSS / Atom / feed teaser

Chat / email preview (by words)

Word mode is ideal when the display width is flexible but you want a fixed word count, e.g. notification titles in IM apps.

Search indexing (full clean text)

Useful before building an FTS index, embeddings, or a simple keyword search. Removes heavy markup overhead while keeping paragraph breaks for readability.

Multilingual share card / og:description

Because truncation is multibyte-safe, CJK characters are never split.

Comment / review sanitized preview

The output contains no tags and no scripts — including entity-encoded ones. Decoding runs after strip_tags, so an encoded &lt;b&gt; — or a &lt;script&gt;alert(1)&lt;/script&gt; — is re-formed into real markup and then stripped again (a hidden element going together with its content). The result can be placed into a text node without any risk of injected markup. Brackets that do not spell a tag, like the &lt; in a &lt; b, are ordinary text and survive.

API

HtmlDigest::extract()

Extracts plain text from HTML and applies smart truncation. Truncation happens after normalization, so the result is clean and never mid-word.

Parameter Type Default Description
$html string — Input HTML. Malformed/partial HTML is tolerated (best-effort).
$length int 200 Truncation limit. Meaning depends on $mode (chars or words). Must be > 0.
$ellipsis string '...' Appended only when truncation actually occurs. Multibyte-safe.
$mode string MODE_CHAR MODE_CHAR (by characters) or MODE_WORD (by words).

Constants

Constant Value Meaning
HtmlDigest::MODE_CHAR 'char' Truncate by character count.
HtmlDigest::MODE_WORD 'word' Truncate by word count.

Returns — the truncated plain-text summary as a string.

Throws HtmlDigestException (extends \RuntimeException):

Condition Example
$length / word count <= 0 HtmlDigest::extract($html, 0)
Unknown $mode HtmlDigest::extract($html, 10, '...', 'bad_mode')
$length smaller than / equal to the ellipsis length (see "Length vs ellipsis" below — not an error, handled gracefully)

HtmlDigest::toText()

Converts HTML to clean plain text — no truncation. This is what extract() uses under the hood.

Returns — normalized plain text with reasonable line breaks.

Processing pipeline:

  1. Removes hidden elements and their content: <script>, <style>, <head>, <noscript>.
  2. Block-level closing tags → newline: </p>, </div>, </li>, </h1>–</h6>, </tr>, </blockquote>, </pre>, </dd>, </dt>; also <br> → newline.
  3. Strips all remaining tags (strip_tags).
  4. Decodes HTML entities (&amp; → &, &lt; → <, &nbsp; → non-breaking space, etc.), then re-strips the markup that decoding re-formed (&lt;script&gt; → <script>): hidden elements first, so their content goes with them, then any remaining tags and comments via a targeted regex (a < followed by a letter) — deliberately narrower than strip_tags, so ordinary text like a &lt;= b or i &lt;3 u survives. An unterminated tag is stripped as well, because a browser closes one at end of input.
  5. Normalizes each line: trims leading/trailing whitespace, collapses runs of whitespace (including &nbsp; and full-width spaces) into a single space.
  6. Drops blank lines (lines containing only whitespace).
  7. Trims Unicode whitespace at the boundaries.

Truncation behavior in detail

Word-boundary rollback (no half-words)

In MODE_CHAR, if the cut point lands in the middle of a word, the result steps back to the last whitespace (space, tab, newline, &nbsp;, or full-width space) so it never shows a broken token:

&nbsp; and full-width spaces are real whitespace

Both are normalized to a single ASCII space in toText(). This means:

CJK (Chinese / Japanese) in word mode

MODE_WORD splits on whitespace, but CJK text has no spaces, so each CJK character is treated as one word-token. CJK tokens are also re-joined without spaces in the output.

Fullwidth punctuation (e.g. , U+FF0C) is part of the CJK token class, so space-less Chinese with punctuation still truncates by character:

Mixed text (e.g. Hello世界) is kept as a single token and counted as one word.

Length vs ellipsis edge cases

Multiline text

Text joined from multiple paragraphs (toText joins with \n) rolls back to the last whitespace across newlines, so trailing content is not dropped:

Limitations & notes

Testing

The suite covers toText() normalization, both truncation modes, CJK handling, Unicode whitespace, ellipsis edge cases, and exception paths — plus a general check that the output stays tag-free however the markup was encoded.

License

MIT


migears/html-digest

Version

以下为中文版 · The Chinese version follows.

面向 PHP 8.1+ 的轻量级 HTML 文本摘要(digest)提取器。将 HTML 转化为干净的纯文本,并执行多字节安全的智能截断——零 DOM 扩展依赖(基于 strip_tags + 正则 + mbstring)。

沿袭 miGears 框架理念:极简、零依赖、几分钟内读完。

特性

边界

范围内

范围外(刻意不做)

安装

快速开始

完整示例:原始 HTML → 提取结果

要直观看到它的价值,请把原始 HTML 与各方法的返回值对照。下面的样本是真实场景:包含隐藏的文档外壳(head/title/script/style)、标题、带内联格式的段落、列表、HTML 实体、&nbsp;、图片与链接。

① 原始 HTML

② toText() —— 所有不可见内容都被清除了

<head>、<title>、<script>、<style> 节点被整体移除;标签被剥除;实体被解码(&amp; → &、&deg; → °);&nbsp; 折叠为空格;每个块独占一行:

没有 script、没有 style、没有 &amp;、没有 &nbsp;、没有 <img> 标签噪音——只剩读者会看到的文字。

③ extract() —— 任意长度的摘要,绝不切断单词

调用 输出
extract($html)(默认 200) ② 中的完整干净文本
extract($html, 30) A Better Morning: How to...
extract($html, 20) A Better...
extract($html, 10) A...
extract($html, 6, '...', MODE_WORD) A Better Morning: How to Brew...

注意词边界:extract($html, 30) 绝不会返回 "A Better Morning: How to Co…"——它会回退到最后一个空白,单词永远不会被切半。

④ 中文样本 —— 中文同样处理良好

调用 输出
toText() 中文冲泡指南 / 水温、粉量与时长的平衡,是手冲咖啡的关键。 多试几次,你会找到自己的偏好。 / 水温 92°C / 粉量 18 克(每行一条)
extract($zh, 20) 中文冲泡指南...
extract($zh, 8, '…', MODE_WORD) 中文冲泡指南水温、粉量与时长的平衡,是手冲咖啡的关键。多试几次,你会找到自己的偏好。…

句中的 &nbsp; 被归一化为空格,°C 得以保留,中文在无空格的词数模式下也能截断(每个汉字按一个词计数)。

实际使用场景

博客 / 文章摘要

body_html 可能是一整段 WYSIWYG 内容(标题、图片、内嵌脚本),但摘要始终干净、绝不会从单词中间断开。

SEO meta description

Google 通常展示约 155 个字符:

实体与残留标记已预先处理,meta 标签里不会出现裸的 &amp; 或 <strong>。

RSS / Atom / Feed 摘要

聊天 / 邮件预览(按词数)

当显示宽度不固定、但想要固定词数时(例如 IM 应用的通知标题),词数模式最合适。

搜索索引(完整纯文本)

在构建全文索引、向量 embedding 或简单关键词搜索前很实用:去掉多余的标记开销,同时保留段落分隔以维持可读性。

多语言分享卡片(og:description)

因为截断是多字节安全的,CJK 字符永远不会被切成两半。

评论 / 评价的安全预览

输出不含任何标签与脚本——包括实体编码的。实体解码发生在 strip_tags 之后,因此编码的 &lt;b&gt;(或 &lt;script&gt;alert(1)&lt;/script&gt;)会先被还原成真标签,再被二次剥除(隐藏元素连同其内容一起剥除)。结果可直接放入文本节点,绝无注入标记的风险。不构成标签的尖括号(如 a &lt; b 中的 &lt;)属于普通文本,会被保留。

API

HtmlDigest::extract()

从 HTML 中提取纯文本并执行智能截断。截断发生在归一化之后,因此结果干净、绝不会从词中间切断。

参数 类型 默认值 说明
$html string — 输入 HTML。对畸形 / 残缺 HTML 尽力容忍。
$length int 200 截断上限。含义取决于 $mode(字符数或词数)。必须 > 0。
$ellipsis string '...' 仅在实际发生截断时追加。多字节安全。
$mode string MODE_CHAR 截断模式:MODE_CHAR(按字符)或 MODE_WORD(按词数)。

常量

常量 取值 含义
HtmlDigest::MODE_CHAR 'char' 按字符数截断。
HtmlDigest::MODE_WORD 'word' 按词数截断。

返回值——截断后的纯文本摘要(string)。

抛出 HtmlDigestException(继承 \RuntimeException):

场景 示例
$length / 词数 <= 0 HtmlDigest::extract($html, 0)
未知的 $mode HtmlDigest::extract($html, 10, '...', 'bad_mode')
$length 小于 / 等于省略号长度 (见下方「length 与省略号」小节——非错误,会被优雅处理)

HtmlDigest::toText()

将 HTML 转化为干净的纯文本——不截断。extract() 内部即调用它。

返回值——带合理换行的归一化纯文本。

处理管线:

  1. 移除隐藏元素及其内容:<script>、<style>、<head>、<noscript>。
  2. 块级闭合标签 → 换行:</p>、</div>、</li>、</h1>–</h6>、</tr>、</blockquote>、</pre>、</dd>、</dt>;<br> 也转成换行。
  3. 剥除其余标签(strip_tags)。
  4. 解码 HTML 实体(&amp; → &、&lt; → <、&nbsp; → 不间断空格等),然后再次剥除解码还原出的标记(如 &lt;script&gt; → <script>):先剥隐藏元素(让其内容一并消失),再用精确正则剥除其余标签与注释(仅识别 < 后跟字母的标记)——刻意比 strip_tags 更窄,使 a &lt;= b、i &lt;3 u 这类普通文本得以保留。未闭合的标签同样会被剥除,因为浏览器会在输入结束时替它闭合。
  5. 逐行归一化:去除行首行尾空白,将连续空白(含 &nbsp; 与全角空格)折叠为一个空格。
  6. 过滤空行(仅含空白的行)。
  7. 修剪边界的 Unicode 空白。

截断行为详解

词边界回退(不截断半个词)

在 MODE_CHAR 下,若切断点落在一个词的中间,结果会回退到最后一个空白(空格、tab、换行、&nbsp;、全角空格),从而不会出现破碎的单词:

&nbsp; 与全角空格都是真正的空白

二者都会在 toText() 中被归一化为一个普通空格。这意味着:

词数模式下的中文 / 日文(CJK)

MODE_WORD 依赖空格分词,但中文没有空格,因此每个汉字被视作一个词。输出时 CJK 字之间不会插入额外空格。

全角标点(如 , U+FF0C)也属于 CJK 词元字符类,因此含标点的无空格中文同样能按字截断:

混合文本(如 Hello世界)整体作为一个词计数,不拆解。

length 与省略号的边界情况

多段文本

由多段落拼接的文本(toText 用 \n 拼接)会回退到跨换行的最后一个空白,不会丢失后段内容:

限制与注意事项

测试

测试覆盖 toText() 归一化、两种截断模式、CJK 处理、Unicode 空白、省略号边界与异常路径,并有一条通用用例断言:无论标签以何种方式编码,输出都保持无标签。

License

MIT


All versions of html-digest with dependencies

PHP Build Version
Package Version
Requires php Version ^8.1
ext-mbstring Version *
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package migears/html-digest contains the following files

Loading the files please wait ...