我怎样才能实现可以使用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标签,然后在上面的div中包装H2部分(所有内容直到下一个H2标签或帖子结尾)?
谢谢:)
答案 0 :(得分:0)
这是一个工作原型,但我强烈建议不要出于性能原因使用这些方法。
<?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);
}
}
你应该把它制成更小的问题,并且能够自己做到这一点: