針對網頁採集常見需求封裝:取得當前腳本 URL、全形轉半形數字、HTML 實體編碼/解碼、相對路徑轉絕對、超連結提取、標籤內容擷取、HTML 表格轉 CSV/二維陣列、英文單詞分詞去重。
function get_php_url() {
if (!empty($_SERVER['REQUEST_URI'])) {
return $_SERVER['REQUEST_URI'];
}
$script = $_SERVER['PHP_SELF'];
return empty($_SERVER['QUERY_STRING']) ? $script : $script . '?' . $_SERVER['QUERY_STRING'];
}
function GetAlabNum($str) {
$full = ['0','1','2','3','4','5','6','7','8','9'];
$half = '0123456789';
$str = str_replace($full, str_split($half), $str);
return preg_replace('/[^0-9\.]|^0+/', '', $str) ?: '0';
}
function Text2Html($txt) {
$txt = str_replace(' ', ' ', $txt);
$txt = str_replace('<', '<', $txt);
$txt = str_replace('>', '>', $txt);
return preg_replace('/[\r\n]+/', "
\r\n", $txt);
}
function ClearHtml($str) {
return str_replace(['<','>'], ['<','>'], $str);
}
function relative_to_absolute($content, $baseUrl) {
if (preg_match('/^(https?|ftp):\/\//', $baseUrl, $m)) $proto = $m[0];
$host = preg_replace('/^(https?|ftp|news):\/\//', '', $baseUrl);
$host = preg_replace('/\/.*/', '', $host);
if (!$host) return $content;
if (isset($proto)) {
$content = preg_replace('/href="\//', 'href="' . $proto . $host . '/', $content);
$content = preg_replace('/src="\//', 'src="' . $proto . $host . '/', $content);
}
return $content;
}
function get_all_url($html) {
preg_match_all('/]*href=["\']?([^"\'\s>]+)["\']?[^>]*>([^<]+)<\/a>/i', $html, $m);
return ['url' => $m[1], 'name' => $m[2]];
}
function get_tag_data($str, $start, $end) {
if (!$start || !$end) return null;
$tmp = explode($start, $str, 2);
if (count($tmp) < 2) return null;
$tmp = explode($end, $tmp[1], 2);
return $tmp[0];
}
function get_tr_array($tableHtml) {
$table = preg_replace('/<\/td>\s*]*>/i', '{td}', $table);
$table = str_replace('', '{tr}', $table);
$table = preg_replace('/<[\/!]*?[^<>]*?>/si', '', $table);
$table = preg_replace('/(\r\n)\s+/', '', $table);
$table = str_replace([' ',' '], '', $table);
$rows = explode('{tr}', $table);
array_pop($rows);
return $rows;
}
8. HTML 表格轉二維陣列(逐儲存格)
function get_td_array($tableHtml) {
$table = preg_replace('/]*>.*<\/thead>/si', '', $tableHtml);
$table = preg_replace('/]*>|<\/tbody>/si', '', $table);
$table = preg_replace('/]*>.*<\/tfoot>/si', '', $table);
$table = str_replace('', '{tr}', $table);
$table = str_replace('', '{td}', $table);
$table = preg_replace('/<[\/!]*?[^<>]*?>/si', '', $table);
$table = preg_replace('/(\r\n)\s+/', '', $table);
$table = str_replace([' ',' '], '', $table);
$rows = explode('{tr}', $table);
array_pop($rows);
$result = [];
foreach ($rows as $row) {
$cells = explode('{td}', $row);
array_pop($cells);
$result[] = $cells;
}
return $result;
}
9. 英文單詞分詞去重排序
function split_en_str($str, $distinct = true) {
preg_match_all('/([a-zA-Z]+)/', $str, $m);
$words = $m[1];
if ($distinct) $words = array_unique($words);
sort($words);
return $words;
}
實務應用建議
- 編碼處理:採集前先偵測網頁編碼(
mb_detect_encoding 或 HTTP Header),統一轉 UTF-8 再處理。
- 反爬蟲:設定 User-Agent、Cookie、Referer、間隔請求、使用 Proxy 池。
- 結構化解析:複雜頁面優先用
DOMDocument + XPath,正則僅作輔助。
- 法律合規:遵守
robots.txt、網站服務條款、個資法(GDPR/PDPA),勿過度請求造成服務阻斷。
現代替代方案
- Goutte:Guzzle + DOMCrawler + CSS 選擇器,適合中小型採集。
- Symfony Panther:支援 JavaScript 渲染(Chrome/Firefox headless),處理 SPA 頁面。
- Scrapy (Python):大型分散式爬蟲框架,生態成熟。
此函數庫適合輕量級、無 JavaScript 渲染需求的採集任務,理解其原理有助於除錯與客製化。
- 上一篇文章: PHP 禁用快取 HTTP 標頭:nocache_headers() 完整實作與應用場景
- 下一篇文章: PHP 多功能圖片處理類 ThumbHandler:縮圖、水印、裁切、翻轉、邊框完整實作
Copyright © 程式碼之家 All Rights Reserved