萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 將 HTML 轉純文字:去除標籤、解碼實體、保留換行

需求場景

  • 搜尋引擎索引內容提取
  • 郵件純文字版本生成
  • API 回傳無標籤摘要
  • 防 XSS 內容清洗

核心函數實作

<?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 指定編碼
&nbsp; 變成亂碼未解碼同上,ENT_HTML5 會處理命名實體
巢狀標籤殘留正則貪婪匹配使用 .*? 非貪婪或 DOMDocument 解析
效能差大字串多次 preg_replace單次正則或用 DOMDocument

替代方案: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 更健壯但較慢,適合複雜結構;正則版適合高效能簡單場景。

copyright © 萬盛學電腦網 all rights reserved