1

This is a continuation from a question I asked earlier about doing this with output from the_excerpt().

What I am trying to do is take the following output from the_content() to take the following output as it currently is:

<h3>Heading</h3>
<p>Paragraph</p>

And have it do the following:

<h3>Heading</h3>
<p><span class="dropcap">P</span>aragraph</p>

I successfully did this with output from the_excerpt() using the following:

$the_excerpt = preg_replace('/^(.)/', '<span class="dropcap">\1</span>', $the_excerpt);

It works perfectly so I borrowed this line of code and modified it to:

$the_content = preg_replace( 
      '/(?<=\<\/h3\>\n<p>)./',
      '<span class="dropcap">\1</span>',
      $the_content
 );

When this filter runs it results in the following output:

<h3>Heading</h3>
<p><span class="dropcap"></span>aragraph</p>

But if I change the '<span class="dropcap">\1</span>' to a static character or string like '@', then it works.

What do I need to change the replacement string to? Seems weird to me that it works in the case of the_excerpt() but not for the_content().

3

The major issue is just that you have a positive lookbehind but no capture group so \1 or $1 isn't a usable variable.

Fix your regex to provide the capture group: '/(?<=\<\/h3\>\n<p>)(.)/' then reference as $1.

ob_start();?>
    <h3>Heading</h3>
    <p>Paragraph</p>
    <p>Paragraph2</p>
<?php

$search = ob_get_clean();    

$result = preg_replace( 
        '/(?<=\<\/h3\>\n<p>)(.)/', 
        '<span class="dropcap">$1</span>', $search );
1

In case this is for styling with CSS you don't need to use a regular expression. With h3 + p:first-letter you should be able to style the first letter of a <p> after a <h3>.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.