我正在整理一个快速脚本来抓取页面以获取一些结果,但我无法弄清楚如何忽略正则表达式中的空格和换行符。
例如,页面可能以 HTML 格式显示结果:
<td class="things">
<div class="stuff">
<p>I need to capture this text.</p>
</div>
</td>
我将如何更改以下正则表达式以忽略空格和新行:
$regex = '/<td class="things"><div class="stuff"><p>(.*)<\/p><\/div><\/td>/i';
如有任何帮助,我们将不胜感激。帮助解释你为什么做某事将不胜感激!
最佳答案
无需提醒您,尝试将正则表达式与 HTML 代码结合使用是在玩火。无论如何回答你的问题,你可以使用这个正则表达式:
$regex='#^<td class="things">\s*<div class="stuff">\s*<p>(.*)</p>\s*</div>\s*</td>#si';
更新:这是基于 DOM 解析器的代码,可获取您想要的内容:
$html = <<< EOF
<td class="things">
<div class="stuff">
<p>I need to capture this text.</p>
</div>
</td>
EOF;
$doc = new DOMDocument();
libxml_use_internal_errors(true);
$doc->loadHTML($html); // loads your html
$xpath = new DOMXPath($doc);
$nodelist = $xpath->query("//td[@class='things']/div[@class='stuff']/p");
for($i=0; $i < $nodelist->length; $i++) {
$node = $nodelist->item($i);
$val = $node->nodeValue;
echo "$val\n"; // prints: I need to capture this text.
}
现在请不要在代码中使用正则表达式来解析 HTML。
关于php - 如何正则表达式抓取 HTML 并忽略代码中的空格和换行符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9999848/