$html = "<a href='https://example.com'>Link 1</a><br/>"
. "<a href='https://example.com'>Link 2</a><br/>";
function stripTheTag(string $html): string {
// 移除所有標籤,保留內容
return preg_replace('@<[/!]*?[^<>]*?>@si', ' ', $html);
}
echo stripTheTag($html); // " Link 1 Link 2 "
缺點:無法處理巢狀標籤、屬性含 >、CDATA、註解、Script/Style 內容殘留。
function extractText(string $html): string {
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML('<?xml encoding="UTF-8"?>' . $html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
libxml_clear_errors();
// 移除 script/style
$xpath = new DOMXPath($dom);
foreach ($xpath->query('//script | //style') as $node) {
$node->parentNode->removeChild($node);
}
return trim(preg_replace('/\s+/', ' ', $dom->textContent));
}
echo extractText($html); // "Link 1 Link 2"
<a> 連結文字與 hreffunction extractLinks(string $html): array {
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML('<?xml encoding="UTF-8"?>' . $html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
libxml_clear_errors();
$links = [];
foreach ($dom->getElementsByTagName('a') as $a) {
$href = $a->getAttribute('href');
$text = trim($a->textContent);
if ($href && $text) {
$links[] = ['text' => $text, 'href' => $href];
}
}
return $links;
}
print_r(extractLinks($html));
/*
Array
(
[0] => Array ( [text] => Link 1 [href] => https://example.com )
[1] => Array ( [text] => Link 2 [href] => https://example.com )
)
*/
function absolutifyUrls(string $html, string $baseUrl): string {
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML('<?xml encoding="UTF-8"?>' . $html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
libxml_clear_errors();
$base = parse_url($baseUrl);
$basePath = rtrim(dirname($base['path']), '/') . '/';
foreach ($dom->getElementsByTagName('a') as $a) {
$href = $a->getAttribute('href');
if ($href && !preg_match('~^https?://~i', $href)) {
if ($href[0] === '/') {
$a->setAttribute('href', $base['scheme'] . '://' . $base['host'] . $href);
} else {
$a->setAttribute('href', $base['scheme'] . '://' . $base['host'] . $basePath . $href);
}
}
}
foreach ($dom->getElementsByTagName('img') as $img) {
$src = $img->getAttribute('src');
if ($src && !preg_match('~^https?://~i', $src)) {
// 同理處理...
}
}
return $dom->saveHTML();
}
| 方法 | 健壯度 | 效能 | 功能 |
|---|---|---|---|
| preg_replace | 低(易壞) | 快 | 單純去標籤 |
| DOMDocument | 高(標準解析) | 中 | 結構化查詢、屬性操作 |
| DOMXPath | 高 | 中 | 複雜選擇器 |
| HTML5 Parser (masterminds/html5) | 最高 | 較慢 | 現代 HTML5 相容 |
HTMLPurifier 過濾後再處理loadHTML 會自動補全標籤,可能改變原始結構XMLReader原始來源:www.111cn.net