It is best idea to use Regular expressions on this type of case. But, as you are using explode()
, and also want a beginner friendly solution, let me help you with explode()
.
Your Mistakes:
- You are using
</p>
as separator, but it will be lost after explode. So your output $explode
wont have these </p>
tags.
</p>
will not work as a separator here, since your $text
contains multiple lines and whitespaces between tags. So, between every </p>
and <h2>
there is some whitespaces and line-breaks.
- If this data/contents generates dynamically, you won't be able to know how many elements you will have after
explode()
. So using index number like $explode[1]
won't help.
Let's talk about solutions:
// Formatted string in $text variable
$text =
"<h2>heading 1</h2>
<p>something</p>
<h2>heading 2</h2>
<p>something</p>
<h2>heading 3</h2>
<p>something</p>
<h2>heading 4</h2>
<p>something</p>
<h2>heading 5</h2>
<p>something</p>
<h2>heading 6</h2>
<p>something</p>
<h2>heading 7</h2>
<p>something</p>
<h2>heading 8</h2>";
// Ad text, will be added after every 4th occurrence of </p>
$ad = "<p>This is an ad</p>";
// Add a | before <h2> tag, this will be our separator on explode
$string = str_replace("<h2", "|<h2", $text);
// this explode will give us an array consists of a h2 and a paragraph as elements.
$text = explode("|", $string);
// Our first element of the array will be blank, cause our explode() replace the
// very first | with a blank array element. That's why we are removing the first
// blank element using array_shift.
array_shift($text);
// $j is a counter variable, this will help us to count every 4th occurrence
$j = 0;
// declare a new array for storing final output
$newText = array();
// using loop, lets add the $ad text
for ($i=0; $i < count($text); $i++) {
$j++;
if ($j == 4) {
// if it is 4th occurrence, add the $ad text
array_push($newText, $text[$i].$ad);
// reset counter to 0.
$j = 0;
}
else{
array_push($newText, $text[$i]);
}
}
// Display the final output
print_r($newText);
Note: If you want only one ad text after the first four paragraph, then you don't need the counter variable $j
, you can check occurrence with $i
variable.
PS: It's much better if you use regex.