Add additional HTML code after the first </p> tag in PHP

Posted in PHP -

I recently made some minor layout changes to my blog including the positioning of the advertising from the top of each article to after the first paragraph. In this post I share the PHP code used to add some additional HTML code after the first closing </p> tag in a page's content.

The content of the web pages in this blog are stored in a database in a MySQL MEDIUMTEXT field (info about MySQL text column storage in one of my blog posts here) and there's no placeholder in the code about where to put the advertising. Before the change on Feb 1st the ads would appear after the article's title and before the first paragraph. I changed this so the advertising would appear after the first paragraph by using the PHP strpos() and substr() functions.

If the content is stored in a variable called $content, we can get the position of the first closing paragraph tag by doing this:

$pos = strpos($content, '</p>');

If the content we want to insert into the $content string is in the variable $extra we can use the substr() function to get all the HTML up to end of the closing </p> tag, add $extra and then append the rest of the $content string like so:

$content = substr($content, 0, $pos+4) . $extra . substr($content, $pos+4);

Breaking this down...

substr($content, 0, $pos+4)

$pos stores the first place in $content that </p> appears, at the position of the < character. To get a substring of everything up to and including the </p> tag we need to add the length of the </p> string to $pos, which is 4.

Next we concatenate $extra and then

substr($content, $pos+4)

Again, we need to add the length of </p> to $pos to get the string from after the occurence of </p>. We could simplify the code a little by adding the +4 to the $pos = line, with the full code looking like so:

$pos = strpos($content, '</p>') + 4;
$content = substr($content, 0, $pos) . $extra . substr($content, $pos);


Related posts:


Comments