In WordPress, I need to italicize a certain phrase in each page’s content

I have a WordPress site that I’m working on, which has a large section of the site that describes plant species. Each plant name begins with “R.”, and is followed by the species name. For example, one instance is “R. adenogynum.” All of these names must be italicized.

There are many instances of this, and to do it by hand would be very time-consuming. I’m trying to write a plugin that will check/italicize all the words in $content, each time “the_content” is run. In other words, I’m using an

Read More
add_filter( 'the_content', 'italicize' )

function italicize($content) {
... 

function to do this.

I’ve tried to use the explode method like so:

$words = explode( ' ', $content );

and then checking each word in the $words array, but the problem is that whitespace and HTML tags also are part of $content, and this jumbles everything. Plus I would have to use implode to put everything back together, which is a bit messy as well.

So how can I edit these plant names successfully with a plugin?

Related posts

Leave a Reply

3 comments

  1. Use regular expressions syntax.

    add_filter( 'the_content', function($content) {
        return preg_replace("/(R. [a-z]+)/", "<i>$1</i>", $content);   
    });
    

    This will match any phrase that begins with “R.” followed by a space, followed by an all lowercase word and replace it with an italicized version of that word.