我找不到任何关于解析此类示例的信息。
<h3 style="color:red; font-size:24px;">This contest is still open.</h3>
这是我的代码,但它不起作用 :( 我要解析这个确切的 H3 标签,因为页面上有很多标签,但它们没有 style="color:red; font- size:24px;"
所以我只想从 H3 返回带有 style="color:red; font-size:24px;"
的内容
$html = get_file_content('http://www.website.com/contest.php');
preg_match( '#<h3[^>]*>(.*?)</h3>#i', $html, $match );
echo $match[1];
最佳答案
你为什么不使用DOMDocument ?它是为解析 HTML 而设计的;正则表达式不是。
$dom = new DOMDocument();
// Assuming it supports URL, if not, put `file_get_contents()` in there.
$dom->loadHTMLFile('http://www.website.com/contest.php');
foreach( $dom->getElemetsByTagName('h3') as $h3) {
if ($h3->hasAttribute('style') AND
$h3->getAttribute('style') == 'color:red; font-size:24px;'
) {
echo $h3->nodeValue;
break;
}
}
关于php 解析带样式的 h 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5560425/