Tip Of The Day: Convert Paragraphs To Returns

/ PHP / by Paul Robinson / 2 Comments
This post was published back on August 30, 2012 and may be outdated. Please use caution when following older tutorials or using older code. After reading be sure to check for newer procedures or updates to code.

While working on a client’s website I needed to add a text area to the user edit screen in WordPress. This was achieved using the various WordPress hooks that WordPress has, but they also requested that it convert double returns into Paragraph tags, just like the WordPress editor. No problem I thought, I’ll just pass it through wpautop() before it’s saved into the user meta data. Worked like a charm, but I hit one odd problem.

The problem? Well the returned text included the paragraphs tags in the text field and removed the returns. Why? Well because it isn’t a WYSIWYG editor. The client preferred we kept a text area here so how do we fix the problem? Well I knocked together a very, very simple bit of REGEX that does the trick and thought I’d share it.

So here it is:

Obviously it won’t match if there are any attributes in the Paragraph tags, but that wasn’t a problem in this case. It basically takes the text with <p> tags as the input and removes them, then it replaces them with the current systems End Of Line character, hence PHP_EOL. Oh, just remember to escape your HTML before putting it into your text area. WordPress users can use the esc_textarea() function.

I hope this little snippet will help someone, as despite how simple it is, it can be very useful. Just remember preg_replace can be hard on system performance, so use it sparingly.

2 Comments

Author’s gravatar

Glad to see a post from you. It’s been a while. Looking forward to more

Reply
Author’s gravatar author

Thanks Jamie,

It’s been pretty crazy the last few weeks. I tend to have an obsession where a post must be ‘so’ long for it to be worthy of a post, but since I haven’t had much time recently I thought it was a better idea to just post something, lol.

Will keep posting little things I pick up when working until I find some time to make a full post, which as mentioned will probably be on Laravel.

Older Comments
Newer Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

I'll keep your WordPress site up-to-date and working to its best.

Find out more