正则表达式以匹配不在特定Div中的标题标签

问题描述 投票:-1回答:3

所以我有PHP代码可以显示如下所示的HTML:

<div class="wrapper">
<h2>This is a header</h2>
<h2>This is one too/h2>
<h4>Here's one</h4>
<div class="ignore">
<h5>I'm one in here too</h5>
</div>
</div>

我想做的是所有标头标签的preg_match_all。我的正则表达式(<h([1-6]{1})[^>]*)>.*<\/h\2>适当地返回了所有它们,但是我不想使用“ ignore”类获取div中的标头。我正在阅读有关消极前瞻的信息,但这很棘手。任何人的帮助将不胜感激。

所需的输出:

<h2>This is a header</h2>
<h2>This is one too/h2>
<h4>Here's one</h4>

请注意,我也是这里的一员,因为它被包裹在div中并带有“ ignore”类。

php regex preg-match
3个回答
1
投票

这里不要弄乱正则表达式-结合DOMDocument查询释放xpath的功能:


0
投票

由于您指定要使用preg_match(),因此下面是一个负向后看的示例(即,过滤掉不以XYZ开头的那些出现:https://regex101.com/r/FeAsuj/1


0
投票

使用DOMDocumentDOMXPath

© www.soinside.com 2019 - 2024. All rights reserved.