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:


And have it do the following:

<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( 
      '<span class="dropcap">\1</span>',

When this filter runs it results in the following output:

<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().

2 Answers 2


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.


$search = ob_get_clean();    

$result = preg_replace( 
        '<span class="dropcap">$1</span>', $search );

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>.

  • I'm using Dropcap.js for more consistency across browsers to handle the styling. I just want PHP to generate the span tags rather than using JavaScript to insert them after the document loads.
    – Cedon
    Nov 6, 2016 at 12:35
  • caniuse.com/#search=First-letter
    – jgraup
    Nov 6, 2016 at 17:00
  • And caniuse.com/#feat=css-sel2 (adjacent sibling selector)
    – Florian
    Nov 8, 2016 at 7:49

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.