【问题标题】:Regex to find html div class content and data-attr? (preg_match_all)正则表达式查找 html div 类内容和数据属性? (preg_match_all)
【发布时间】:2018-08-10 03:17:03
【问题描述】:

使用 preg_match_all 我想在 html 中获取类和数据属性。

以下示例有效,它只返回名称只返回data-id内容。

我希望示例模式同时查找类和数据 ID 内容。

我应该使用哪种正则表达式模式?

HTML 内容:

<!-- I want to: $matches[1] == test_class  | $matches[2] == null -->
<div class="test_class"> 

<!-- I want to: $matches[1] == test_class | $matches[2] == 1 -->
<div class="test_class" data-id="1"> 

<!-- I want to: $matches[1] == test_class | $matches[2] == 1 -->
<div id="test_id" class="test_class" data-id="1">

<!-- I want to: $matches[1] == test_class test_class2 | $matches[2] == 1 -->
<div class="test_class test_class2" id="test_id" data-id="1">

<!-- I want to: $matches[1] == 1 | $matches[2] == test_class test_class2 -->
<div data-id="1" class="test_class test_class2" id="test_id" >

<!-- I want to: $matches[1] == 1 | $matches[2] == test_class test_class2 -->
<div id="test_id" data-id="1" class="test_class test_class2">

<!-- I want to: $matches[1] == test_class | $matches[2] == 1 -->
<div class="test_class" id="test_id" data-id="1">

无法正常工作的正则表达式:

$pattern = '/<(div|i)\s.*(class|data-id)="([^"]+)"[^>]*>/i';

preg_match_all($pattern, $content, $matches, PREG_SET_ORDER);

提前致谢。

【问题讨论】:

标签: php html regex preg-match-all


【解决方案1】:

为什么不使用 DOM 解析器呢?

您可以使用像 //div[@class or @data-id] 这样的 XPath 表达式来定位元素,然后提取它们的属性值

$doc = new DOMDocument();
$doc->loadHTML($html);

$xpath = new DOMXpath($doc);
$divs = $xpath->query('//div[@class or @data-id]');
foreach ($divs as $div) {
  $matches = [$div->getAttribute('class'), $div->getAttribute('data-id')];
  print_r($matches);
}

演示~https://eval.in/1046227

【讨论】:

  • 非常感谢!我也可以用这种方法分解 CSS 内容吗?
  • @MertA。我不太确定您的意思,但可能不是;你不能用 DOM 解析器解析 CSS
  • 对不起,我正在更正:我正在使用此方法更改 html 类名。我正在用另一个代码结构更改 css 文件中的类名。我在 php 中使用正则表达式,同时更改 css 文件中的类名。我想知道我是否可以使用 php 来处理 DOM?
  • @MertA。不,您不能使用 DOM 解析器读取、解释或修改 CSS。不过,您可以更改 HTML 中的值。
【解决方案2】:

我第二菲尔的回答,我认为 HTML 解析器是要走的路。它更安全,可以处理很多复杂的事情。

话虽如此,如果你想在你的例子中尝试正则表达式,它会是这样的:

<(?:div|i)(?:.*?(?:class|data-id)="([^"]+)")?(?:.*?(?:class|data-id)="([^"]+)")?[^>]*>

示例:https://regex101.com/r/Gb82lF/1/

【讨论】:

  • 感谢您所做的事情,我一直在寻找几个小时。是的,我认为使用 DOM 很方便。埃瓦拉兄弟。
  • 你好@Ibrahim。我需要你给我的代码。但是有这样的问题请帮助我? regex101.com/r/vSIsac/3
  • 嗨@MertA.,您可以用[^\&lt;]*? 替换.*? 以防止标签在里面。示例:regex101.com/r/vSIsac/6
  • 非常感谢!! @Ibrahim 我以为我会迟到,所以我问了新问题。请将答案写在问题url中:stackoverflow.com/questions/51794647/…
  • @MertA。欢迎 :) 关于 div 中的data-ss is not accepted,是因为你没有添加=
猜你喜欢
  • 2013-01-23
  • 1970-01-01
  • 2012-11-26
  • 1970-01-01
  • 2010-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多