【发布时间】:2013-07-27 02:55:18
【问题描述】:
我的正则表达式很差,这是我的场景,
我正在尝试从包含多个表格的网页中提取一些信息,只有一些表格包含唯一的 url(比如说“very/unique.key”),所以它看起来像这样:
<table ....>
(bunch of content)
</table>
<table ....>
(bunch of content)
</table>
<table ....>
(bunch of content + "very/unique.key" keyword)
</table>
<table ....>
(bunch of content)
</table>
<table ....>
(bunch of content + "very/unique.key" keyword)
</table>
所以我想要的是提取所有包含“very/unique.key”关键字的表格内容。这是我尝试过的模式:
$pattern = "#<table[^>]+>((?!\<table)(?=very\/unique\.key).*)<\/table>#i";
这对我没有任何回报......
$pattern = "#<table[^>]+>((?!<table).*)<\/table>#i";
这将返回从表 1 的打开标记 <table...> 到最后一个表的结束标记 </table> 的所有内容,即使使用 (?!<table) 条件...
感谢任何愿意帮助我的人,谢谢。
--编辑--
这是我找到的使用 DOM 循环遍历每个表的解决方案
--我的解决方案--
$index;//indexes of all the table(s) that contains the keyword
$cd = 0;//counter
$DOM = new DOMDocument();
$DOM->loadHTMLFile("http://uni.corp/sub/sub/target.php?key=123");
$xpath = new DomXPath($DOM);
$tables = $DOM->getElementsByTagName("table");
for ($n = 0; $n < $tables->length; $n++) {
$rows = $tables->item($n)->getElementsByTagName("tr");
for ($i = 0; $i < $rows->length; $i++) {
$cols = $rows->item($i)->getElementsbyTagName("td");
for ($j = 0; $j < $cols->length; $j++) {
$td = $cols->item($j); // grab the td element
$img = $xpath->query('./img',$td)->item(0); // grab the first direct img child element
if(isset($img) ){
$image = $img->getAttribute('src'); // grab the source of the image
echo $image;
if($image == "very/unique.key"){
echo $cols->item($j)->nodeValue, "\t";
$index[$cd] = $n;
if($n > $cd){
$cd++;
}
echo $cd . " " . $n;//for troubleshooting
}
}
}
echo "<br/>";
}
}
//loop that echo out only the table(s) that I want which contains the keyword
$loop = sizeof($index);
for ($n = 0; $n < $loop; $n++) {
$temp = $index[$n];
$rows = $tables->item($temp)->getElementsbyTagName("tr");
for ($i = 0; $i < $rows->length; $i++) {
$cols = $rows->item($i)->getElementsbyTagName("td");
for ($j = 0; $j < $cols->length; $j++) {
echo $cols->item($j)->nodeValue, "\t";
//proccess the extracted table content here
}
//echo "<br/>";
}
}
但就个人而言,我仍然对正则表达式部分感到好奇,希望任何人都可以找到解决这个问题的正则表达式模式。无论如何,感谢所有在这方面帮助/建议我的人(尤其是 AbsoluteƵERØ)。
【问题讨论】:
-
为什么首先使用正则表达式?怎么样:php.net/manual/en/class.domelement.php
-
不要使用正则表达式解析 HTML。您无法使用正则表达式可靠地解析 HTML,并且您将面临悲伤和挫败感。一旦 HTML 与您的期望发生变化,您的代码就会被破坏。有关如何使用已经编写、测试和调试的 PHP 模块正确解析 HTML 的示例,请参阅 htmlparsing.com/php。
-
这似乎是XY problem。您真正的问题/问题是如何获取包含上述字符串的表格元素。使用正则表达式只是一种解决方案,此外并没有真正加起来。
-
我试图解析/提取的网页是一个动态页面,它使用 AJAX/php/JS 生成动态内容。因此,网页中的大多数 html 元素都没有任何唯一标识符,例如 id/class。而且由于内容是动态的,所以我觉得使用 DOM 进行解析可能要困难得多,尽管我的正则表达式也很差。这是一个 Intranet 网页,我用它来解析一定数量的信息,这些信息不应该超过 1 个月(我猜)。感谢您回复我,并感谢任何人都可以使用 DOM 或 Regex 或其他任何方式启发我更多...
标签: php regex html-parsing