title: How to add a custom paragraph after x number of paragraphs with php
body: <p>I'm working in somebodies old website, he got this piece of php code that puts in an advertisement div inside the content after the 4th paragraph. It's working alright. The idea is: <code>explode</code>ing  the <code>&lt;/p&gt;</code> tags, counting them in a loop, adding the new div after the 4th iteration,  putting everything back together. </p>
  
  <p>The problem with this function is that it counts ALL paragraphs, and I need only the paragraph with no attributes (classes, ID's etc.). Only normal clean <code>&lt;p&gt;</code> tags.</p>
  
  <p>Here is the code I'm using now:</p>
  
  <pre><code>    $paragraphAfter = 4; //Enter number of paragraphs to display ad after.
      $content = explode("&lt;/p&gt;", $content);
      $new_content = '';
          for ($i = 0; $i &lt; count($content); $i++) {
              if ($i == $paragraphAfter) {
                  $new_content.= '&lt;div id="adsuser"&gt;';
                          $new_content.= '&lt;h3 style="font-weight:bold; margin:0px"&gt;'.get_the_title().'&lt;/h3&gt;';
                          $new_content.= '&lt;p style="margin:0px; background-color:rgba(255,255,0,0.3); line-height:1.2em"&gt;'.get_the_excerpt().'&lt;/p&gt;';
                          $new_content.= '&lt;/div&gt;&lt;div id="sealads"&gt;&lt;/div&gt;';
              }
          $new_content.= $content[$i] . "&lt;/p&gt;";
          }
  
      wp_reset_postdata();
      $new_content .= '&lt;p style="font-size:145%; text-align:center"&gt;&lt;a href="http://www.bayadaim.org.il/%D7%A4%D7%95%D7%A8%D7%95%D7%9D-%D7%91%D7%99%D7%93%D7%99%D7%99%D7%9D/" style=""&gt;נשארת עם המון שאלות? רוצה לפתוח דיון בנושא?&lt;br/&gt; פורום "בידיים" מחכה לך!&lt;/a&gt;&lt;/p&gt;';
      return $new_content;
  </code></pre>
  
  <p>I've tried several things, including <code>preg_split</code>, but it seems I'm using it wrong because I always end up with a messy content without <code>&lt;p&gt;</code> tags or with too many.</p>
  
  <p>Thanks a lot,
  Itamar</p>