简体   繁体   中英

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

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?

This is a job best suited to preg_replace .

Your function would look something like this:

function italicize_plant_names ($content) {  
    $content = preg_replace('(R\.\s+\w+)', '<em>$0</em>', $content);
    return content;
}

Demo of the php code , and Regular Expression tester

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.

Try this plugin: http://urbangiraffe.com/plugins/search-regex/

It allows you to do a regex search and search/replace for your phrase.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM