【问题标题】:How to preg_match_all to get the text inside the tags "<h3>" and "<h3> <a/> </h3>"如何 preg_match_all 获取标签“<h3>”和“<h3> <a/> </h3>”内的文本
【发布时间】:2021-05-27 04:11:35
【问题描述】:

您好,我目前正在为我的 wordpress 网站创建一个自动目录。我的参考来自 https://webdeasy.de/en/wordpress-table-of-contents-without-plugin/

问题: 除非在&lt;h3&gt; 标签中有&lt;a&gt; 标签链接,否则一切顺利。它使$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];

上面的代码用于查找&lt;h3&gt; &lt;a&gt; a text &lt;/a&gt; &lt;h3&gt;标签中的文本,但是不包含&lt;a&gt;标签的h3标签是个问题。

我的问题: 如何结合上面的代码? 我的期望是,如果第一个代码结果没有出现,那么它会执行第二个代码作为结果。

或者也许有更好的解决方案?谢谢。

【问题讨论】:

  • 有一个更好的解决方案,就是不使用正则表达式解析HTML(见this)。相反,请使用更合适的工具,例如 DOMDocument

标签: php html regex wordpress preg-match-all


【解决方案1】:

这是一种删除标题标签内所有标签的方法

$html = <<<EOT
<h3>Here's an <a href="thing.php">alternative solution</a></h3> to using regex. <h3>It may <a name='#thing'>not</a></h3> be the most elegant solution, but it works
EOT;

preg_match_all('#<h(.*?)>(.*?)<\/h(.*?)>#si', $html, $matches);
foreach ($matches[0] as $num=>$blah) {
   $look_for = preg_quote($matches[0][$num],"/");
   $tag = str_replace("<","",explode(">",$matches[0][$num])[0]);
   $replace_with = "<$tag>" . strip_tags($matches[2][$num]) . "</$tag>";
   $html = preg_replace("/$look_for/", $replace_with,$html,1);
}

echo "<pre>$html</pre>";

【讨论】:

    【解决方案2】:

    答案@kinglish 是这个解决方案的基础,非常感谢。我根据我的问题文章链接稍微修改和简化它。这段代码对我有用:

    preg_match_all('#(\<h[3-4])\sid=\"(.*?)\"?\>(.*?)(<\/h[3-4]>)#si',$content, $matches);    
        $tags = $matches[0];
        $ids = $matches[2];
        $raw_names = $matches[3];
        /* Clean $rawnames from other html tags */
        $clean_names= array_map(function($v){
            return trim(strip_tags($v));
        }, $raw_names);
        $names = $clean_names;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-11
      • 2018-05-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多