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:
$text = preg_replace('#<p>(.*)&;lt;\/p>#i', "$1".PHP_EOL, $text);
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
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.