<?php
/**
* 將 HTML 轉為純文字
* @param string $html 輸入 HTML
* @param bool $keepLineBreaks 是否保留區塊元素換行
* @return string
*/
function html_to_text(string $html, bool $keepLineBreaks = true): string {
// 1. 移除 script/style 及其內容
$html = preg_replace('/<(script|style)[^>]*>.*?<\/\1>/is', '', $html);
// 2. 區塊元素轉換為換行(可選)
if ($keepLineBreaks) {
$blockTags = ['div', 'p', 'br', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
'li', 'tr', 'td', 'th', 'blockquote', 'section', 'article'];
foreach ($blockTags as $tag) {
$html = preg_replace("/<\/?$tag[^>]*>/i", "\n", $html);
}
}
// 3. 移除所有剩餘標籤
$html = preg_replace('/<[^>]+>/', '', $html);
// 4. 解碼 HTML 實體
$html = html_entity_decode($html, ENT_QUOTES | ENT_HTML5, 'UTF-8');
// 5. 正規化空白字元
$html = preg_replace('/[ \t]+/', ' ', $html); // 多空格/Tab → 單空格
$html = preg_replace('/\n{3,}/', "\n\n", $html); // 多餘換行壓縮
$html = trim($html);
return $html;
}
// 使用範例
$html = '<div><h1>標題</h1><p>內容 包含<strong>粗體</strong>.</p><script>alert(1)</script></div>';
echo html_to_text($html);
// 輸出:
// 標題
// 內容 包含粗體.
function html_to_text_advanced(string $html, array $allowedTags = []): string {
if ($allowedTags) {
// 先保護允許的標籤
$placeholders = [];
foreach ($allowedTags as $tag) {
$placeholder = "{{ALLOWED_$tag}}";
$html = preg_replace("/<\/?$tag[^>]*>/i", $placeholder, $html);
$placeholders[$placeholder] = $tag;
}
// 移除其他標籤
$html = preg_replace('/<[^>]+>/', '', $html);
// 還原允許標籤
$html = str_replace(array_keys($placeholders), array_values($placeholders), $html);
} else {
$html = preg_replace('/<[^>]+>/', '', $html);
}
return html_entity_decode($html, ENT_QUOTES | ENT_HTML5, 'UTF-8');
}
| 問題 | 原因 | 解決 |
|---|---|---|
| 中文亂碼 | 編碼不一致 | 確保輸入為 UTF-8,html_entity_decode 指定編碼 |
| 變成亂碼 | 未解碼 | 同上,ENT_HTML5 會處理命名實體 |
| 巢狀標籤殘留 | 正則貪婪匹配 | 使用 .*? 非貪婪或 DOMDocument 解析 |
| 效能差 | 大字串多次 preg_replace | 單次正則或用 DOMDocument |
function html_to_text_dom(string $html): string {
$dom = new DOMDocument();
@$dom->loadHTML('<meta charset="utf-8">' . $html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
return trim($dom->textContent);
}
DOMDocument 更健壯但較慢,適合複雜結構;正則版適合高效能簡單場景。