php 解析带样式的 h 标签

标签 php parsing

我找不到任何关于解析此类示例的信息。

<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/

相关文章:

php - 您如何在PHP中解析和处理HTML/XML?

javascript - 基于多个因素转换 Javascript 数组

python - 匹配 AWK 中多行的正则表达式。 && 运算符(operator)?

c# - 如何使用 HtmlAgilityPack 获取表单中的所有输入元素而不会出现空引用错误

php - 向类(class)添加 moodle (3.1.7) 事件时出现黑屏

PHP 本地服务器无效请求(意外的 EOF)

php - PHP 的 EBNF 语法定义?

php - 为范围内的每个日期插入行

javascript - 使用 JSON 显示两个图表

javascript - 带有解析的 iOS HTML InnerText