How to insert ads after an “h2, p, h3, etc…” tag

This code below is well known on the internet, I tried several times to change it and make it not only count the

tag as a paragraph, but the , , etc. tags. Does anyone have an idea how to do this?

Insert ad after second paragraph of single post content.

function prefix_insert_after_paragraph2( $ ads, $ content ) { if ( ! is_array( $ ads ) ) { return $ content; } $ closing_p = ‘

‘; $ paragraphs = explode( $ closing_p, $ content );

foreach ($  paragraphs as $  index => $  paragraph) {     if ( trim( $  paragraph ) ) {         $  paragraphs[$  index] .= $  closing_p;     }      $  n = $  index + 1;      if ( isset( $  ads[ $  n ] ) ) {         $  paragraphs[$  index] .= $  ads[ $  n ];     } }  return implode( '', $  paragraphs ); 

}

add_filter( ‘the_content’, ‘prefix_insert_post_ads’ );

function prefix_insert_post_ads( $ content ) { if ( is_single() && ! is_admin() ) { $ content = prefix_insert_after_paragraph2( array( // The format is: ‘{PARAGRAPH_NUMBER}’ => ‘AD_CODE’, ‘1’ => ‘ ad code 1 goes here ‘, ‘6’ => ‘ ad code 2 goes here’, ), $ content ); }

return $  content; 

}