Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
268 views
in Technique[技术] by (71.8m points)

php - Avoiding getting text wrapped around the code tag when text is with certain tag

I am using a Wordpress plugin that puts the code tag around text that is in backticks for highlighting purposes on my blog. Now the original function is this:

function mdc_the_content( $content ) {

    $content = preg_replace( '/`(.*?)`/', '<code>$1</code>', $content );
    return $content;

} // mdc_the_content
add_filter( 'the_content', 'mdc_the_content' );

When I am using js highlighter plugin (code highlighter) then it places the code tag around the code that is in backticks. I want to avoid that. Would the function below work? Only put the code tag around tags when the backticks are not wrapped in <pre class="EnlighterJSRAW" data-enlighter-language="r">$1</pre>. Would the if statement below work? Sometimes there might be multiple objects wrapped around backticks within the highlighter. Thank you.

function mdc_the_content( $content ) {

    if(!preg_match('/`(.*?)`/', '<pre class="EnlighterJSRAW" data-enlighter-language="r">$1</pre>', $content)) {
        $content = preg_replace( '/`(.*?)`/', '<code>$1</code>', $content );
    }

    return $content;

} // mdc_the_content
add_filter( 'the_content', 'mdc_the_content' );
question from:https://stackoverflow.com/questions/65857323/avoiding-getting-text-wrapped-around-the-code-tag-when-text-is-with-certain-tag

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use

$content = preg_replace( '~<pres+class="EnlighterJSRAW"s+data-enlighter-language="r">.*?</pre>(*SKIP)(*F)|`(.*?)`~s', '<code>$1</code>', $content );

See the regex demo.

The <pres+class="EnlighterJSRAW"s+data-enlighter-language="r">.*?</pre>(*SKIP)(*F)| part matches the pre tag with two specific attributes allowing any amount of whitespace and all contents in it, and the `(.*?)` will match in all other contexts.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...