預設情況下,正則表達式中的點號 . 不匹配換行符(\n/\r)。當目標 HTML 跨多行時,需開啟「單行模式」(Single-line mode,又稱 DOTALL)。
<?php
$html = '<span class="realm tip" id="profile-info-realm" data-battlegroup="US">
Some content here
</span>';
// 錯誤:預設模式無法跨行匹配
$pattern1 = '/<span class="realm tip" id="profile-info-realm" data-battlegroup="(.*)">
(.*)<\/span>/i';
// 正確:加上 s 修飾符,讓 . 匹配換行符
$pattern2 = '/<span class="realm tip" id="profile-info-realm" data-battlegroup="(.*)">
(.*)<\/span>/is';
preg_match($pattern2, $html, $matches);
print_r($matches);
/* 輸出:
Array (
[0] => 完整匹配字串
[1] => US
[2] => Some content here
)
*/
?>
| 修飾符 | 名稱 | 作用 |
|---|---|---|
i | PCRE_CASELESS | 大小寫不敏感 |
s | PCRE_DOTALL | 點號匹配換行符(關鍵) |
m | PCRE_MULTILINE | ^ $ 匹配每行首尾(非整字串) |
x | PCRE_EXTENDED | 忽略空白、允許註解,提升可讀性 |
u | PCRE_UTF8 | 正確處理 UTF-8 字元(中文必加) |
<?php
// 爬蟲常用組合:忽略大小寫 + 跨行匹配 + UTF-8
$pattern = '/<div class="content">(.*?)<\/div>/isu';
// 複雜正則建議用 x 模式分行加註解
$pattern = '/
<span\s+class="realm\s+tip" # 起始標籤
\s+id="profile-info-realm" # 固定 id
\s+data-battlegroup="([^"]+)" # 捕獲戰群
\s*> # 標籤結束
(.*?) # 非貪婪捕獲內容
<\/span> # 結束標籤
/ixu'; // i=不分大小寫, x=延伸模式, u=UTF-8
?>
強烈建議:HTML 解析請用 DOMDocument 或 DOMXPath,健壯度遠超正則:
<?php
$dom = new DOMDocument();
@$dom->loadHTML($html); // 抑制非標準 HTML 警告
$xpath = new DOMXPath($dom);
$nodes = $xpath->query('//span[@id="profile-info-realm"]');
foreach ($nodes as $node) {
echo $node->getAttribute('data-battlegroup'); // US
echo $node->textContent; // Some content here
}
?>