首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 解析 HTML 字串的四大核心方法:strip_tags、正則、DOMDocument、Simple HTML DOM

     編輯:PHP 相關知識

方法對比總覽

方法適用場景優點缺點依賴
strip_tags()快速移除所有標籤、保留特定標籤內建、極快、記憶體少無法處理屬性、巢狀邏輯、破碎 HTML無
strpos + substr固定結構、單一標籤提取零依賴、可控極其脆弱、維護困難無
DOMDocument標準化、結構化操作、XPath 查詢W3C 標準、支援 HTML5 (libxml)、健壯效能較低、編碼處理麻煩PHP 核心
Simple HTML DOM快速開發、jQuery 風格選擇器API 直覺、容錯強、支援 CSS 選擇器純 PHP 實現較慢、大檔案記憶體大第三方庫

1. strip_tags():最輕量的淨化

<?php
$html = '<div><p class="lead">Hello <b>World</b>!</p><script>alert(1)</script></div>';

// 移除所有標籤
echo strip_tags($html); // Hello World!

// 保留 <p> <b>
echo strip_tags($html, '<p><b>'); // <p class="lead">Hello <b>World</b>!</p>

// ⚠️ 屬性保留:strip_tags 不會移除屬性(如 class、onclick),XSS 風險!
// 生產環境必須搭配 HTMLPurifier 深度淨化
?>

2. DOMDocument:標準化結構操作

<?php
$html = '<ul><li id="a">Item A</li><li id="b">Item B</li></ul>';

$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML('<meta charset="utf-8">' . $html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
libxml_clear_errors();

$xpath = new DOMXPath($dom);

// 查詢所有 li
foreach ($xpath->query('//li') as $li) {
    echo "ID: {$li->getAttribute('id')}, Text: {$li->nodeValue}<br>";
}

// 修改內容
$firstLi = $xpath->query('//li[1]')->item(0);
$firstLi->nodeValue = 'Updated A';
$firstLi->setAttribute('class', 'active');

// 輸出
echo $dom->saveHTML();
?>

3. Simple HTML DOM:爬蟲首選

<?php
require_once 'simple_html_dom.php';

$html = file_get_html('https://example.com/articles');

// CSS 選擇器提取
foreach ($html->find('article h2 a') as $link) {
    echo $link->href . ' - ' . $link->plaintext . '<br>';
}

// 修改 DOM
$html->find('div.content', 0)->innertext = '<p>New Content</p>';
echo $html->save();

// 記憶體釋放(重要!)
$html->clear();
unset($html);
?>

4. 正則表達式:特定模式提取(不推薦通用解析)

<?php
$html = '<img src="photo.jpg" alt="Photo"> <img src="pic.png" alt="Pic">';

// 僅提取 src
preg_match_all('/<img[^>]+src=["\']([^"\']+)["\']/i', $html, $matches);
print_r($matches[1]); // ['photo.jpg', 'pic.png']

// ⚠️ 正則無法正確處理巢狀、跨行、屬性順序變化,僅用於極簡單固定格式
?>

選型決策樹

  1. 只需純文字摘要 → strip_tags() + mb_substr()
  2. 需提取特定屬性/結構、專案已用 Composer → Simple HTML DOM 或 symfony/dom-crawler
  3. 需嚴格標準合規、XPath 複雜查詢、無第三方依賴 → DOMDocument
  4. 超大檔案(>10MB)流式處理 → XMLReader (SAX 模式)

安全提醒

  • 任何來自用戶輸入的 HTML 輸出前,必須經過 HTMLPurifier 淨化
  • strip_tags() 保留標籤時會保留屬性(含 onclick、style),極高 XSS 風險
  • 解析外部網頁時設定 libxml_disable_entity_loader(true) 防止 XXE 攻擊
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved