Php 正则表达式:如何提取HTML标题标记
提取所有标题标签(h1、h2、h3等)及其内容。例如:Php 正则表达式:如何提取HTML标题标记,php,regex,Php,Regex,提取所有标题标签(h1、h2、h3等)及其内容。例如: <h1 id="title">This is the title</h1> <h2 id="subtitle">This is the subtitle</h2> <p>And this is the paragraph</p> 这是标题 这是副标题 这是一段 将提取为: 这是标题和这是副标题 我正在使用PHP并使用regex作为标题。建议使用右边的代码来完成任务
<h1 id="title">This is the title</h1>
<h2 id="subtitle">This is the subtitle</h2>
<p>And this is the paragraph</p>
这是标题
这是副标题
这是一段
将提取为:
这是标题
和这是副标题
我正在使用PHP并使用regex作为标题。建议使用右边的代码来完成任务
$doc = DOMDocument::loadHTML('
<h1 id="title">This is the title</h1>
<h2 id="subtitle">This is the subtitle</h2>
<p>And this is the paragraph</p>
<p>another tag</p>
');
$xpath = new DOMXPath($doc);
$heads = $xpath->query('//h1|//h2|//h3|//h4|//h5|//h6');
foreach ($heads as $tag) {
echo $doc->saveHTML($tag), "\n";
}
$doc=DOMDocument::loadHTML('
这是标题
这是副标题
这是一段
另一个标签
');
$xpath=新的DOMXPath($doc);
$heads=$xpath->query('//h1 |//h2 |//h3 |//h4 |//h5 |//h6');
foreach($heads作为$tag){
echo$doc->saveHTML($tag),“\n”;
}
输出
<h1 id="title">This is the title</h1>
<h2 id="subtitle">This is the subtitle</h2>
这是标题
这是副标题
您使用的是什么语言?解析器对于这项任务来说是相当容易的。Regexp不应该适合实现您想要的,您想要使用的是innerHtml
请提供更多信息我使用的是PHP和regexSo,您使用的是什么regex?如果那是你喜欢的,你可能已经试过了?你遇到了什么问题?