1
I am rebuilding an old project, written in PHP with Mysql. For practical purposes, consider it as a news portal.
In the database there are several articles, which I list on the site by simple query, which generates the strings $title $subtitle and $content.
I need to put an advertising banner in the middle of the $content text. I thought of breaking $content into lines to then put the advertising code block, but preferably after the first or second paragraph.
So what is the most recommended way to do this, in practice? Break a string into rows and identify paragraphs (preg_split() ?), inject what I need after the second and print the rest?
Updating
Note: Paragraphs of $content are separated by <br><br>
, recorded in the database.
I got to the code below, based on the comment of Dvdsamm, but it doesn’t work properly, showing only the text without including <div>BANNER</div>
after the second paragraph as expected.
$conteudo = ''.$x['conteudo'].'';
// adiciona banner
function addBanner($i)
{
static $conta = 0;
$retorno = $i[0];
if(++$conta == 2){
$retorno .= "<div>BANNER</div>";
}
return $retorno;
}
$txt = preg_replace_callback('#(<br><br>)#', 'addBanner', $conteudo);
// adiciona banner
echo"$txt";
Are you using any WYSIWYG editor or
textarea
raw?– Vitor Adriano
Pure PHP, without Framework. That was the question?
– Leonel Junior
Your paragraphs are always within <p></p>?
– Sam
Yes, within <p></p>
– Leonel Junior
Take a look at this Ideone. The function, using
preg_replace_callback()
, places content (in this case, a DIV) between the second and third paragraph. But it only works 1 time because of the variablestatic
. As I am not in depth mt in PHP, I don’t know how to solve it. But it might already be an idea.– Sam
Thank you for answering, Dvdsamm. It turns out that my paragraphs are all (together) within (the same) <p></p>. So your proposal does not resolve. But I believe it can be a very interesting starting point because of the following: the paragraphs are separated by <br><br> recorded in the database, so I thought to adapt, as code I included in the question.
– Leonel Junior
How do I use this code and instead of just inserting a banner, I can include two banners. In different paragraphs.
– Gladison