【发布时间】:2021-05-27 04:11:35
【问题描述】:
您好,我目前正在为我的 wordpress 网站创建一个自动目录。我的参考来自 https://webdeasy.de/en/wordpress-table-of-contents-without-plugin/
问题:
除非在<h3> 标签中有<a> 标签链接,否则一切顺利。它使$names 结果丢失。
我看到这个正则表达式部分的问题
preg_match_all("/<h[3,4](?:\sid=\"(.*)\")?(?:.*)?>(.*)<\/h[3,4]>/", $content, $matches);
// get text under <h3> or <h4> tag.
$names = $matches[2];
我试过修改正则表达式(我不太明白)
preg_match_all (/ <h [3,4] (?: \ sid = \ "(. *) \")? (?:. *)?> <a (. *)> (. *) <\ / a> <\ / h [3,4]> /", $content, $matches)
// get text under <a> tag.
$names = $matches[4];
上面的代码用于查找<h3> <a> a text </a> <h3>标签中的文本,但是不包含<a>标签的h3标签是个问题。
我的问题: 如何结合上面的代码? 我的期望是,如果第一个代码结果没有出现,那么它会执行第二个代码作为结果。
或者也许有更好的解决方案?谢谢。
【问题讨论】:
-
有一个更好的解决方案,就是不使用正则表达式解析HTML(见this)。相反,请使用更合适的工具,例如 DOMDocument
标签: php html regex wordpress preg-match-all