萬盛學電腦網

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

PHP 內容提取類:從網頁抓取 URL、Email、圖片並支援替換處理

功能概覽

Grep 類封裝常見內容提取需求:從 HTML/文字中提取 **URL (超連結)**、**Email**、**圖片連結**,並支援**回調替換**處理(如轉換為短連結、加密 Email、CDN 域名替換)。

完整類代碼

<?php
/**
 * Grep - 內容模式提取與替換工具類
 * 支援類型:url, email, image
 */
class Grep {
    /** @var array 預設正則模式 */
    private array $patterns = [
        'url'   => '/]*href\s*=\s*["\']((?:https?|ftp):\/\/[^"\'>\s]+)["\'][^>]*>/si',
        'email' => '/\b[\w\.-]+@[\w\.-]+\.\w{2,}\b/',
        'image' => '/]*src\s*=\s*["\'](https?:\/\/[^"\'>\s]+\.(?:jpg|jpeg|gif|bmp|png|webp))["\'][^>]*>/i',
    ];

    private string $content = '';

    /** 設置待處理內容 */
    public function setContent(string $content): self {
        $this->content = $content;
        return $this;
    }

    /** 獲取指定類型的所有匹配
     * @param string $type url|email|image
     * @param bool $unique 是否去重
     * @return array
     */
    public function get(string $type, bool $unique = false): array {
        $type = strtolower($type);
        if ($this->content === '' || !isset($this->patterns[$type])) return [];
        
        preg_match_all($this->patterns[$type], $this->content, $matches);
        $result = $matches[1] ?? []; // 取捕獲組
        return $unique ? array_unique($result) : $result;
    }

    /** 替換指定類型內容
     * @param string $type url|email|image
     * @param callable $callback 接收 matches 陣列,返回替換字串
     * @return string 替換後內容
     */
    public function replace(string $type, callable $callback): string {
        $type = strtolower($type);
        if ($this->content === '' || !isset($this->patterns[$type]) || !$callback) {
            return $this->content;
        }
        return preg_replace_callback($this->patterns[$type], $callback, $this->content);
    }

    /** 新增/覆蓋自定義模式 */
    public function setPattern(string $type, string $pattern): self {
        $this->patterns[strtolower($type)] = $pattern;
        return $this;
    }

    /** 獲取當前模式 */
    public function getPattern(string $type): string {
        return $this->patterns[strtolower($type)] ?? '';
    }
}

使用範例

1. 抓取遠端頁面並提取資源

<?php
require 'Grep.php';

$html = file_get_contents('https://example.com/article/123');
$grep = new Grep();
$grep->setContent($html);

// 提取所有連結 (去重)
$urls = $grep->get('url', true);
echo "找到 " . count($urls) . " 個連結:\n";
print_r($urls);

// 提取 Email (去重)
$emails = $grep->get('email', true);
echo "Email: " . implode(', ', $emails) . "\n";

// 提取圖片
$images = $grep->get('image', true);
echo "圖片數: " . count($images) . "\n";

2. 內容安全處理:URL 轉短連結、Email 反爬蟲混淆、圖片指向 CDN

<?php
$processed = $grep->replace('url', function($m) {
    // $m[0] 完整匹配 ..., $m[1] 為 URL
    $short = shortenUrl($m[1]); // 你的短網址服務
    return str_replace($m[1], $short, $m[0]);
});

$processed = $grep->replace('email', function($m) {
    // $m[0] 為完整 email
    return '';
});

$processed = $grep->replace('image', function($m) {
    // $m[1] 為圖片 URL
    $cdnUrl = 'https://cdn.my.com/' . parse_url($m[1], PHP_URL_PATH);
    return str_replace($m[1], $cdnUrl, $m[0]);
});

echo $processed;

3. 自定義模式:提取電話號碼

<?php
$grep->setPattern('phone', '/(?:\+?86[- ]?)?1[3-9]\d{9}/');
$phones = $grep->get('phone', true);
// 輸出: ['13800138000', '+86 139 1234 5678', ...]

正則模式設計說明

類型模式捕獲組說明
url`/]*href\s*=\s*["\']((?:https?|ftp):\/\/[^"\'>\s]+)["\'][^>]*>/si`1: 完整 URL匹配 ``,支援單雙引號、屬性順序不固定、忽略大小寫
email`/\b[\w\.-]+@[\w\.-]+\.\w{2,}\b/`0: 完整 email簡易 RFC 5322 子集,足夠 99% 場景
image`/]*src\s*=\s*["\'](https?:\/\/[^"\'>\s]+\.(?:jpg|jpeg|gif|bmp|png|webp))["\'][^>]*>/i`1: 圖片 URL限定常見圖片副檔名,避免匹配 CSS background-image 等

效能與限制

  • **正則解析 HTML 非萬能**:巢狀標籤、屬性含 `>`、JS 動態生成內容會遺漏/誤判
  • **大型文檔建議用 DOMDocument**:
    $dom = new DOMDocument();
        libxml_use_internal_errors(true);
        $dom->loadHTML($html);
        $links = $dom->getElementsByTagName('a');
        foreach ($links as $a) { $urls[] = $a->getAttribute('href'); }
  • **串流處理**:超大文件 (>10MB) 考慮 `XMLReader` (SAX) 或分塊處理

擴展建議

  • 加入 **Schema.org / Open Graph / Twitter Card** 結構化數據提取
  • 整合 **Readability** 算法提取正文內容(去除導航、廣告、側邊欄)
  • 支援 **流式處理**:`setContentFromStream($fp)` 避免大字串佔用記憶體
  • 增加 **快取層**:相同 URL 內容快取 1 小時,避免重複抓取

總結:`Grep` 類為輕量級內容提取提供了統一介面,適合爬蟲、編輯器預覽、內容安全過濾等場景。複雜 HTML 結構解析請改用 DOM/XPath。

copyright © 萬盛學電腦網 all rights reserved