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)] ?? '';
}
}
<?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";
<?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 '[email protected]';
});
$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;
<?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 | 匹配 ``,支援單雙引號、屬性順序不固定、忽略大小寫 |
| `/\b[\w\.-]+@[\w\.-]+\.\w{2,}\b/` | 0: 完整 email | 簡易 RFC 5322 子集,足夠 99% 場景 | |
| image | `/ | 1: 圖片 URL | 限定常見圖片副檔名,避免匹配 CSS background-image 等 |
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML($html);
$links = $dom->getElementsByTagName('a');
foreach ($links as $a) { $urls[] = $a->getAttribute('href'); }
總結:`Grep` 類為輕量級內容提取提供了統一介面,適合爬蟲、編輯器預覽、內容安全過濾等場景。複雜 HTML 結構解析請改用 DOM/XPath。