PHP preg_match() First Letter of a WordPress Post for Drop Cap Styling

by Yang Yang on June 15, 2012

Drop Cap ExampleWhile CSS3 can target the first letter of text inside an element, it’s still not universally supported across major browsers AND it doesn’t work well for elements that have child elements inside. The bullet proof way to target the first letter of a WordPress post would be to capture the content of the post in WordPress theme and match it by regular expression functions in PHP, such as preg_match().

And here’s the code I’ve come up for this job:

ob_start();
the_content();
$content = ob_get_clean();
$content = preg_replace('@<p>\s*((?:<[^<>]+>\s*)*)([^<>\s])@'
, '<p>$1<span class="drop_cap">$2</span>'
, $content
, 1);

echo $content;

Obviously, this code should reside in single.php of your WordPress theme where the content of the posts is being output. Just replace any “the_content()” function in the post area with this snippet.

The key is the regular expressions:

@<p>\s*((?:<[^<>]+>\s*)*)([^<>\s])@

And:

<p>$1<span class="drop_cap">$2</span>

That finds the 1st non-whitespace, printable character (a letter, a numeral, etc.) of a post and adds a surrounding <span> tag with class “drop_cap” to it.

Now you will add some drop cap styles to style.css as class .drop_cap, and the first letter of your posts will have a nice drop cap style. See this blog Mosso Reviews for example.

irsah June 15, 2012 at 8:16 pm

Thks YY. Would try it out on my clients WP. Luv the work.

Yang Yang June 24, 2012 at 11:33 pm

Thanks. Glad it helped out. 🙂

Sylvio October 2, 2012 at 3:07 am

It doesn’t work!!!!!!!!!!!

Comments on this entry are closed.

Previous post:

Next post: