如何实现这样的目标:我可以使用PHP循环来循环through`the_content()的WordPress帖子/页面,查找H2标记并将每个H2部分包装在一个div中?
我想在以下两种情况下进行交替:
<div class="content animate-on-view fadeInUp wrap">和
<div class="content even animate-on-view fadeInUp wrap">但我不知道如何做到这一点。如何获取post内容并找到H2标记,然后在上面的div中包装H2部分(直到下一个H2标记或帖子的末尾)?
谢谢:)
发布于 2016-10-09 19:43:12
这是一个工作原型,但出于性能原因,我强烈建议不要使用这种方法。
<?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);
}
}你应该把这个问题分解成更小的问题,这样你就可以自己解决了:
https://stackoverflow.com/questions/39947361
复制相似问题