[英]Regular Expression in PHP: How to create a pattern for tables in html
我正在使用最新的PHP。 我想解析HTML頁面以獲取數據。
HTML:
<table class="margin15" style="margin-left: 0pt; margin-right: 0pt;" width="100%" align="left" border="0" cellpadding="0" cellspacing="0">
TRs, TDs, Data
</table>
<table class="margin15" style="margin-left: 0pt; margin-right: 0pt;" width="100%" align="left" border="0" cellpadding="0" cellspacing="0">
TRs, TDs, Data
</table>
<table class="margin15" style="margin-left: 0pt; margin-right: 0pt;" width="100%" align="left" border="0" cellpadding="0" cellspacing="0">
TRs, TDs, Data
</table>
<table class="margin15" style="margin-left: 0pt; margin-right: 0pt;" width="100%" align="left" border="0" cellpadding="0" cellspacing="0">
TRs, TDs, Data
</table>
PHP代碼:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.test.com/mypage.html');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
$pattern = '/<table class="margin15" style="margin-left: 0pt; margin-right: 0pt;" width="100%" align="left" border="1" cellpadding="0" cellspacing="0">[^~]</table>/';
preg_match_all($pattern, $result, $matches);
print_r($matches);
?>
我無法獲取所有表格。 當我使用簡單的$ pattern ='/ table /'; ,它給了我確切的結果。 如何創建模式以將整個表放在一個數組位置?
使用regex解析HTML充其量是一件痛苦的事情,因為HTML不是常規的,我建議您使用Simple HTML DOM 。
請看一下這個答案 。 它描述了PHP想要使用HTML解析器的用途。
或僅使用php所提供的DOM類。 我認為它可以執行與簡單html dom相同的操作,但速度要快得多(不要誤會,我真的很喜歡Simple Html DOM,但是對於只有幾十行的文件來說速度很慢)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.