萬盛學電腦網

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

PHP 正則擷取 HTML 連結文字:preg_replace 移除標籤、DOMDocument 解析、安全過濾

需求:從 HTML 字串提取純文字

$html = "<a href='https://example.com'>Link 1</a><br/>"
      . "<a href='https://example.com'>Link 2</a><br/>";

方法一:preg_replace 移除所有標籤(簡易、脆弱)

function stripTheTag(string $html): string {
    // 移除所有標籤,保留內容
    return preg_replace('@<[/!]*?[^<>]*?>@si', ' ', $html);
}

echo stripTheTag($html); // " Link 1   Link 2 "

缺點:無法處理巢狀標籤、屬性含 >、CDATA、註解、Script/Style 內容殘留。

方法二:DOMDocument 正規解析(推薦)

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> 連結文字與 href

function 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 相容

安全提醒

  • 不可信 HTML 輸入必須用 HTMLPurifier 過濾後再處理
  • loadHTML 會自動補全標籤,可能改變原始結構
  • 大量文件處理考慮 SAX 模式 XMLReader

原始來源:www.111cn.net

copyright © 萬盛學電腦網 all rights reserved