【问题标题】:PHP WordPress Foreach H2 Heading in HTMLHTML 中的 PHP WordPress Foreach H2 标题
【发布时间】:2016-10-09 18:58:36
【问题描述】:

如何实现可以使用 PHP foreach 循环的方法,该循环将遍历 WordPress 帖子/页面的`the_content(),找到 H2 标签并将每个 H2 部分包装在一个 div 中?

我想交替使用:

<div class="content animate-on-view fadeInUp wrap">

<div class="content even animate-on-view fadeInUp wrap">

但我不确定如何实现这一点。如何获取帖子内容并找到 H2 标签,然后将 H2 部分(直到下一个 H2 标签或帖子结尾的所有内容)包装在上述 div 中?

谢谢:)

【问题讨论】:

  • if ($i % 2 == 0) echo 'even';
  • @u_mulder 我需要先找到 H2。
  • 对此有什么想法吗?

标签: php html css wordpress


【解决方案1】:

这是一个工作原型,但出于性能原因,我强烈建议不要使用此类方法。

<?php
ob_start();
?>
<h2>Lorem Ipsum is simply dummy text of the printing</h2> and typesetting industry. <h2>Lorem Ipsum has been the industry's</h2> standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
<?php
$text = ob_get_contents();
$tagname = "h2";
$regex = "#<\s*?$tagname\b[^>]*>(.*?)</$tagname\b[^>]*>#s";
preg_match_all($regex, $text, $matches);
for($i=0;$i<count($matches[0]);$i++)
{
    if ($i % 2 == 0)
    {
        $text = str_replace($matches[0][$i], '<div class="content animate-on-view fadeInUp wrap">'.$matches[0][$i].'</div>', $text);
    }
    else
    {
        $text = str_replace($matches[0][$i], '<div class="content even animate-on-view fadeInUp wrap">'.$matches[0][$i].'</div>', $text);
    }
}

您应该将其分解为较小的问题,并且可以自己解决:

  1. How to match content between html tags with REGEX
  2. 遍历结果并使用奇/偶测试在您想要的标签之间进行更改...

【讨论】:

  • 如果标题有

    等标签怎么办?那我觉得这行不通?

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-04
  • 2021-12-11
  • 1970-01-01
  • 2019-01-07
  • 2015-11-11
  • 1970-01-01
相关资源
最近更新 更多