How to insert a context advertisement in the body of articles using PHP?

Inserting an ad in the body of the article using PHP

Dear visitors of the blog Today I would like to discuss how to insert a code of context advertisement in
the body of articles
using the PHP language (ru).

Some rules of placing advertisement in the body of articles

      1. It is no good when there are too many ads in the body of the article and it complicates the reading.
      2. Also it is not convenient when the advertisement code goes right under the title of the article and it’s hard to understand where the title and the advertisement code are. After the article’s title an ad should be inserted at least between two first paragraphs.
      3. You don’t want to insert the ad in the center of the paragraph thus breaking it into two parts. It’s better to insert a context ad between the paragraphs.
      4. It would be good if ad blocks are separated by one thousand or more characters.


Inserting an ad between paragraphs of the article

In order to insert a block of context ad , it is necessary to determine places for advertisement block in the body of article using the rules described above. In harmony with these rules, this is a space between the paragraphs. How to get the needed values which will indicate such places between the paragraphs?

To this end, let’s use a function of the PHP language explode. The function explode(string $separator, string $string ) returns an array of strings obtained as a result of splitting the stringstring using separator. In this case the argument of function string is the body of the article in which we are inserting the ad code. And the argument of function separator is a string “</p>”, which will be a separator.


$tag = "</p>";
$pieces = explode($tag, $text);


After using the function explode we will receive an array $pieces, consisting of the article’s paragraphs. Now we want to highlight and save unique strings of the article that will indicate the places in the text where we need to add the blocks of a context ad.


function ins_adv($text)
$block = "Here your ad code must be inserted";
// an array consisting of strings which must be replaced with the ad block 
// an array consisting of strings with the ad block which will be inserted 
// between the paragraphs of the article
$arr = array();
$arr1 = array();
foreach ($pieces as $piece) {
	$txt.= $piece;
	// Now check the number of characters in order to comply with rule 4
	//of ad placement in the body of articles 
	if (strlen(strip_tags($txt))>1200)
		// add a separator at the end $tag,
		// i.e. strings are added to the array without it.
		$arr[] = substr($piece, -250).$tag; 
		$arr1[] = substr($piece, -250).$tag.$block;
		$txt=''; $i+=1;
	if ($i==3) {break;}
return str_replace($arr, $arr1, $text);


As it is evident from the above-given code, using the cycle we are checking all elements of the array $pieces, in order to save each 250 characters at the end of the paragraph in the array $arr. We also save $arr1 these 250 characters at the end of the paragraph in the array with the ad block at the end in order to replace it in the required places of the text later on.

In harmony with the rules 4 of ad placement in the text of the articles we have to place ad blocks on the basis of one block per minimum 1,000 characters of the text. Therefore in the cycle of our code there is a condition that checks the number of characters in the paragraphs without counting the characters of HTML and PHP tags. (here we are using the function strip_tags to remove HTML and PHP tags from the string).

As soon as the number of characters exceeds 1,200, we save this place in the body of the article between the paragraphs. As it is already described in the code, we add a separator $tag at the end of the unique string since strings are added to the array without it.

The condition of the cycle checks that not more than three blocks of context advertisement be inserted in the body of the article. This condition is necessary because for example in harmony with the terms of Google AdSense ad placement on the website page
it is possible to place not more than three blocks of the context ad. If you place more, the ad will not appear anyway and you will violate the terms of ad placement on the website. By the way, you can create your own account in Google (ru).

Now the easiest part: to replace those places in the body of the article that we saved for the context ad. To this end, we are using a PHP function str_replace; it replaces an array of strings in the text with an array of strings with our ad.

A function for replacing a tag <!–advertisement–> in the body of the article

It happens that it is better to indicate the places in the body of the article in advance in order to insert the block of the context ad. It can be done by placing tag <!–advertisement–> in the selected places of the article. Then to replace these places with the context ad using a programming method.


function change_tag_advertisement($text)

// replace a tag using a regular expression 
$count = null;
return preg_replace('~<!--advertisement-->~', $adsense, trim($text), 2, $count);



As it is evident from the above-given code, we replace a tag <!–advertisement–>, using the function preg_replace, that does a search and replacement according to the regular expression . Why it is more convenient to place advertisement using this method? Because you can determine the most suitable places in the body of the article in advance so that they completely comply with the rules of ad placement in the body of the article.

Combining methods of ads insertion in the body of the articles for achieving the best results

What if you have articles where you have already placed a tag <!–advertisement–> in suitable places, and in other places you want automatic placement of context ad ? How to combine these two methods? There is nothing difficult. You can do the following:


function join_adv_methods($text)

// if there is at least one tag <!--advertisement-->, we replace it 
// and return the body of the article 
if (substr_count($text, '<!--advertisement-->') >= 1)
	return change_tag_advertisement($text);
} else {
	return ins_adv($text);


As it is evident from the code above, additional condition was added at the beginning of the join_adv_methods function. This conditions checks the number of tag <!–advertisement–>. This is done using a PHP function substr_count, that returns the number of tag entries <!–advertisement–> in the body of the article. If no tag was found, the context ad is placed automatically . If you want to create an individual design of the your website, please, read the article how to create a working website out of a template (ru).

That’s all! I hope it was explained in detail! Good luck in mastering PHP!

13 replies
    • softmaker says:

      Hi, Dave! You can change my function ins_adv($text) and inject your ad after fourth iteration of the loop.

  1. ratios financiers says:

    Hi terrific website! Does running a blog such as this take a large amount
    of work? I have virtually no knowledge of coding however I was hoping to start my own blog soon.
    Anyways, if you have any ideas or tips for new blog owners
    please share. I understand this is off subject however I simply wanted to ask.
    Thank you!

  2. Nila says:

    I appreciate, lead to I discovered just what I was looking
    for. You’ve ended my 4 day long hunt! God Bless you man. Have a nice
    day. Bye

  3. LorenGDubill says:

    Everyone loves the things you guys tend to be up too.
    This type of clever work and coverage! Continue the terrific works
    guys I’ve included you guys to my blogroll.

  4. LilaEJahnsen says:

    wonderful points altogether, you just won a brand new reader.
    What would you recommend in regards to your publish
    which you made some days previously? Any sure?

  5. BennieEDzama says:

    Nice post. I learn something new and challenging on sites I stumbleupon on a daily basis.

    It will always be interesting to read articles from other writers and use a little something from their

  6. WayneJFencil says:

    Good day! I could have sworn I’ve visited this web site before but after looking at lots of the posts I realized
    it’s new to me. Nonetheless, I’m definitely pleased I stumbled upon it and I’ll be bookmarking it and checking back

  7. StasiaYAlert says:

    Good blog you possess got here.. It’s difficult to acquire high
    quality writing like yours today. I honestly appreciate individuals as if you!
    Be cautious!!

  8. StantonQHopp says:

    I each and every time spent my half an hour to read this website’s articles everyday together with a cup of coffee.

Comments are closed.