douxia1988 2013-07-28 00:17
浏览 48

使用PHP有一种方法可以检测是否有两个不间断的元素出现?

This is a difficult question for me to word correctly, but I am trying to dynamically insert an ASIDE [specifically, just a "special thanks" note] between paragraphs. Initially I decided to drop this after the second paragraph by using substr_count(). I am floating this block, so if all it had to deal with was textual content there was no issue word-wrapping it. However, if it ran adjacent to an image or a PRE or anything else, it got wonky.

Anyway, what I want to do is detect when there is the first occurrence of TWO adjacent paragraphs and insert my aside between those. I.e.:

<p> Here is the first paragraph. </p>
<aside> INSERT THIS HERE </aside>
<p> Here is the second paragraph. </p>

Thoughts are appreciated.

Update: the substr_count() I am currently using.

Because I got voted down for not showing the original code, I'll post it below. I am using Wordpress but this isn't a WP specific question, as I'm taking the_content() as the string, counting the occurrences of P, and inserting the custom field there. This is ultimately not what I want to do, but I want to count two concurrent P's and insert this field between. It may be formatted strangely, as of course when I c/p from my editor stuff was all over the place.

$thanks = get_post_meta(get_the_ID(), 'thanks', true);

if (!$thanks) {
  the_content();
}

else {
  $show_after_p = 0;
  $content = apply_filters('the_content', $post->post_content);
  if(substr_count($content, '<p>') > $show_after_p) {
$contents = explode("</p>", $content);
$p_count = 0;
foreach($contents as $content)
     {
   echo $content;
   if($p_count == $show_after_p)
  {
?>
<aside class="thanks clearfix">
    <p>
      <?php echo '<span>Special thanks: </span>'.$thanks; ?>
    </p>
</aside>
<?php } 
echo "</p>";
$p_count++;
}
}
}
?>

Why not JS? Well, javascript could definitely do this, but if I can do this in PHP then yahtzee.

  • 写回答

2条回答 默认 最新

  • doujupa7567 2013-07-28 00:37
    关注

    use regular expression and preg_replace - search for: (closing of P){whitespaces (if any)}(opening P) and change whitespaces to your text.

    something like that:

     $content = preg_replace('#</p>\s*<p#', "</p><aside> INSERT THIS HERE </aside><p", $content);
    
    评论

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c