Comments

I just started doing this and ya, this is a perpetual problem. Not so much with sites that I manage but for clients. Carriage returns (or lack there of) and a client that like to play with the WYSIWYG editor and you have a recipe for disaster.

In the past I’ve used the following bit of JS in situations where the user might have JS turned off, there alternative doesn’t break anything… Not really the same and certainly not as reliable, but can provide you with some added flexibility.

Hi there, James thanks for posting the link. I was looking for exactly this (how to strip the p tags from around iframes too). The Fublo blog isn’t there anymore, can anyone suggest how it’s to be done?

Hi Leif, wondered if you could you help me understand the difference between your preg_replace and the original code snippet above. Yours works for me and the original doesn’t, and I’m trying to understand why :)

This website is the best resource for CSS and beyond, never fails to provide answers to typical problems without the usual bs intro’s. Straight to the point with concise solutions that work. Beautiful design too! Thank you, Thank you, Thank you!

This didn’t work for me initially… after fighting with regex for a couple of hours, I discovered that the problem was due to WordPress not putting an end </p> tag in (in my case the image is directly followed by a shortcode which I think was mucking things up). The browser automatically corrects – hence the </p> shows in console etc, but when I view source, it’s not there.

Wow! I came across the issue in 2016 (after 5 years of your post). It actually did the trick but it failed when the <IMG> has alignment class which is wrapped around <P> along with the plain text. like below<p><img class="alignright" src="" />Paragraph text here</p>
However I could make the following expression for this

Unfortunately this still won’t function if the paragraph text comes before the image tag. e.g. if an image is placed right between some paragraph text like below.<p>Text Before The Image<img class="alignright" src="" />Text After The Image</p>
I tried the last (group) of ‘anything’ in the regexp (.*?) by putting it before the first group, making them total of 3 groups. But it didn’t work as I expected.

We have a pretty good* newsletter.

Email Address

CSS-Tricks* is created, written by, and maintained by Chris Coyier and a team of swell people. It is built on WordPress, hosted by Media Temple, and the assets are served by MaxCDN. The fonts are Source Sans Pro and Source Code Pro. It is made possible through sponsorships from products and services we like.