[英]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.