如何从字符串中提取PHP中的标题标记

blu*_*iel 5 php text preg-match

从包含大量HTMl的字符串中,如何将<h1><h2>etc标记中的所有文本提取到新变量中.

可能使用preg_match_all并将匹配发送到单个逗号分隔变量.

多谢你们.

小智 6

首先,您需要使用tidy清理HTML(示例中为$ html_str):

$tidy_config = array(
    "indent"               => true,
    "output-xml"           => true,
    "output-xhtml"         => false,
    "drop-empty-paras"     => false,
    "hide-comments"        => true,
    "numeric-entities"     => true,
    "doctype"              => "omit",
    "char-encoding"        => "utf8",
    "repeated-attributes"  => "keep-last"
);

$xml_str = tidy_repair_string($html_str, $tidy_config);
Run Code Online (Sandbox Code Playgroud)

然后,您可以将XML($ xml_str)加载到DOMDocument中:

$doc = DOMDocument::loadXML($xml_str);
Run Code Online (Sandbox Code Playgroud)

最后你可以使用Horia Dragomir的方法:

$list = $doc->getElementsByTagName("h1");
for ($i = 0; $i < $list->length; $i++) {
    print($list->item($i)->nodeValue . "<br/>\n");
}
Run Code Online (Sandbox Code Playgroud)

或者您也可以在DOMDocument上使用XPath进行更复杂的查询(请参阅http://www.php.net/manual/en/class.domxpath.php)

$xpath = new DOMXPath($doc);
$list = $xpath->evaluate("//h1");
Run Code Online (Sandbox Code Playgroud)


Sco*_*ers 2

如果你真的想使用正则表达式,我认为:

preg_match_all('/<h[0-6]>([^</h[0-6]>*)</h/i', $string, $matches);
Run Code Online (Sandbox Code Playgroud)

只要您的标头标签未嵌套,就应该可以工作。正如其他人所说,如果您无法控制 HTML,那么正则表达式并不是实现此目的的好方法。