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

PHP 內容提取類 Grep:擷取/替換 URL、Email、圖片標籤

     編輯:PHP 綜合知識

功能概覽

Grep 類別以正則表達式從 HTML/文本中提取或替換三類內容:

  • URL:<a href="url">...</a>
  • Email:admin@domain.com
  • Image:<img src="image.jpg">

核心代碼 (Grep.class.php)

<?php
class Grep {
    private $_pattern = [
        'url'   => '/<a.*?href="((http(s)?:\/\/).*?)".*?/si',
        'email' => '/([\w\-\.]+@[\w\-\.]+(\.\w+))/',
        'image' => '/<img.*?src="([^"]+\.(jpg|jpeg|gif|bmp|png))"/i'
    ];
    private $_content = '';

    public function set($content) { $this->_content = $content; }

    public function get($type) {
        if (!isset($this->_pattern[$type])) return [];
        preg_match_all($this->_pattern[$type], $this->_content, $matches);
        return $matches[1] ?? [];
    }

    public function replace($type, $replacement) {
        if (!isset($this->_pattern[$type])) return $this->_content;
        return preg_replace($this->_pattern[$type], $replacement, $this->_content);
    }
}

使用範例

$html = '<a href="https://example.com">Link</a> Contact: test@mail.com <img src="photo.jpg">';
$grep = new Grep();
$grep->set($html);

print_r($grep->get('url'));   // ['https://example.com']
print_r($grep->get('email')); // ['test@mail.com']
print_r($grep->get('image')); // ['photo.jpg']

// 替換:將所有連結指向代理
$safeHtml = $grep->replace('url', '<a href="/proxy?url=$1">$1</a>');

正則模式解析

類型正則捕獲組
URL/<a.*?href="((http(s)?:\/\/).*?)".*?/si完整 URL (含協議)
Email/([\w\-\.]+@[\w\-\.]+(\.\w+))/完整 Email
Image/<img.*?src="([^"]+\.(jpg|jpeg|gif|bmp|png))"/i圖片 URL

擴充建議

  • 支援單引號屬性值:href='...'。
  • 提取 srcset、data-src 等現代屬性。
  • 加入 DOMDocument 解析器備選,處理巢狀/不標準 HTML 更健壯。
  • 提供 callback 替換模式,允許動態計算替換值。

結語

Grep 以極簡封裝滿足常見內容提取/替換需求。正則雖快但難以覆蓋所有 HTML 邊界案例,關鍵系統建議引入 DOMDocument 或 Masterminds/HTML5-Parser 以換取解析可靠性。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved