撰寫網頁爬蟲或資料采集程式時,常需從 HTML 原始碼中提取標題、作者、正文等區塊。本文提供兩種通用解析函式:正則表達式版與字串分割版。
<?php
// 正則表達式擷取:$start 與 $end 為正則模式
function preg_substr($start, $end, $str) {
$temp = preg_split($start, $str);
$content = preg_split($end, $temp[1]);
return $content[0];
}
// 字串分割擷取:$start 與 $end 為純字串
function str_substr($start, $end, $str) {
$temp = explode($start, $str, 2);
$content = explode($end, $temp[1], 2);
return $content[0];
}
?>
<?php
// 取得遠端頁面並轉碼(視目標網站編碼調整)
$url = 'https://example.com/article/123';
$html = iconv('UTF-8', 'GB2312//IGNORE', file_get_contents($url));
// 1. 擷取標題 ...
$title = str_substr('', ' ', $html);
echo "標題: $title\n";
// 2. 正則擷取作者連結 作者名
$author = preg_substr('/userid=\d+">', '', $html);
echo "作者: $author\n";
// 3. 擷取內容區塊 ...
$content = str_substr('', '', $html);
echo "內容: $content\n";
?>
| 特性 | preg_substr (正則) | str_substr (字串分割) |
|---|---|---|
| 靈活度 | 高(支援複雜模式) | 低(固定字串) |
| 效能 | 較慢 | 極快 |
| 適用場景 | 標籤屬性不固定、需模糊匹配 | 結構固定、明確標記 |
| 編碼敏感度 | 需注意模式編碼一致 | 直接比對位元組 |