How to use PHP to insert content after or before HTML tag

The problem is quite simple…you just want to count a specific tag on a page and insert some content. After or before it’s just a matter of perspective. So let’s say you want an ad, for example, to be inserted, after the fourth H2 tag. So let’s go and insert an ad code or any other content block after some HTML tag. Here we have a simple PHP function: …and you can simply call it like this: This will place,  $myAd in $myContent, after the fourth occurrence of the closing tag </h2>  if there are at least 8 occurrences of the mentioned tag. That was simple, was it? Now let’s get a little bit more complicated.

Insert block before HTML tag occurrence

And how about if you need to add the content, before the fourth title? Let’s do that. You will only have to change the tag to the HTML opening tag, change the order where all the content is printed.

Insert block before or after an alternative tag

Now let’s imagine we want to insert an ad after the third title on the page. But if we don’t have enough titles on the page we just want to place an ad after the fourth paragraph. That is a reasonable scenario, isn’t it? So let’s modify our function. Instead of returning the content when the minimum number of elements is not found, we will just search for the $alternativeTag as we did in the first place. At this point, you can just let the function continue because you are using the alternative tag.

And the final mixed function

This is how ower final PHP function will look like. You can use it to add content blocks after a certain number of HTML tag occurrences. ….and this is the way you call it to insert a block before the fourth H2 tag. If you do not have 8 H2 it will use the H3 tag. Since almost all the params have a default value into the function definition, you can just adjust that to your needs and just call the function with the required $my_content  var. Note: Of course, there are other scenarios and you can build a  robust function or even class to achieve a more dynamic usage. For example, you can use an array of elements to split the content, you can add an if to switch between after and before depending on the tag structure, etc. Feel free to do that, adapt it to your needs.

Leave a Reply

Your email address will not be published. Required fields are marked *