'PHP: Insert marker every 3 iterations

I have the following:

<?php
  $content = apply_filters( 'the_content', get_the_content() );
        
  $content_table = explode("<p>", $content);

  $content_table[3] .= $spot1;
  $content_table[6] .= $spot2;
  $content_table[9] .= $spot3;
  $content_table[12] .= $spot4;
  $content_table[15] .= $spot5;

  $content2 = implode($content_table, "<p>");
        
  echo $content2;
?>

This grabs the content from the page (Wordpress) and then after each 3rd paragraph inserts a custom shortcode (ie. $spot1) - this works great, but it only applies to paragraphs.

I also want to include heading tags in the count - this code only applies to paragraphs.



Solution 1:[1]

You can explode on multiple delimiters like so:

$content_table = explode(["<p>", "<h1>", "<h2>"], $content);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mikerojas