I'm 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 are on the site by simple query, which generates the strings $ title $ subtitle and $ content.
I need to put an ad banner in the middle of the text $ content. I thought about breaking $ content in lines to then put the block of advertising code, but preferably after the first or second paragraph.
So, what is the best way to do this in practice? I want to break the string into lines and identify the paragraphs (preg_split ()?), Inject what I need after the second and print the rest?
Upgrading
Note: The paragraphs in the $ content are separated by <br><br>
, saved in the database.
I came to the code below, based on the comment from Dvdsamm, but it does not work correctly, 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";