首页
学习
活动
专区
圈层
工具
发布

H2标题
EN

Stack Overflow用户
提问于 2016-10-09 18:58:36
回答 1查看 904关注 0票数 0

如何实现这样的目标:我可以使用PHP循环来循环through`the_content()的WordPress帖子/页面,查找H2标记并将每个H2部分包装在一个div中?

我想在以下两种情况下进行交替:

代码语言:javascript
复制
<div class="content animate-on-view fadeInUp wrap">

代码语言:javascript
复制
<div class="content even animate-on-view fadeInUp wrap">

但我不知道如何做到这一点。如何获取post内容并找到H2标记,然后在上面的div中包装H2部分(直到下一个H2标记或帖子的末尾)?

谢谢:)

EN

回答 1

Stack Overflow用户

发布于 2016-10-09 19:43:12

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

代码语言:javascript
复制
<?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. 迭代结果,并使用奇数/偶数测试在所需的标记之间进行更改.
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39947361

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档