Regular Expression in PHP: How to create a pattern for tables in html

允我心安 提交于 2019-12-11 06:23:41

问题


I am using latest PHP. I want to parse HTML page to get data.

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 Code:

<?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);

?>

I am not able to get all tables. When I use simple $pattern='/table/';, it gives me exact result. How to create a pattern to get whole table at one array location?


回答1:


Parsing HTML using regex is a pain at best as HTML is not regular, I suggest you use Simple HTML DOM.




回答2:


You can't parse [X]HTML with regex, but you can try:

$pattern = '#<table(?:.*?)>(.*?)</table>#';

This won't work if there are nested tables.




回答3:


Please have a look at this answer. It describes the usage of an HTML parser in PHP, which is what you want to do.




回答4:


Or just use the DOM class php offers. I think it can do the same as simple html dom but much faster (don't' get me wrong, I really like Simple Html DOM, but it's slow for files with a few dozen lines)



来源:https://stackoverflow.com/questions/1902115/regular-expression-in-php-how-to-create-a-pattern-for-tables-in-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!