The Personal Website of Ash M. White

Convert Plain-Text Writing Into HTML Paragraphs

by Ash White / 02.05.10

Something that has always irked me is having to take the value of a textarea and convert the text into HTML paragraphs (especially when using a WYSIWYG is not an option). Here's a quick PHP snippet to take care of that, whether the user uses one or two line breaks for new paragraphs.

$body = preg_replace("/\r/", "\n", $body);
$body = preg_replace("/(\n+)/", "</p><p>", $body);
$body = "<p>$body</p>";

The first line will convert all carriage returns into newline characters (to accommodate for the way different operating systems handle line breaks). The second line will replace one or more occurrences of a newline into an ending and open paragraph tag. From there, all you need to do it wrap the entire block in a paragraph tag, which is taken care of by the third line.

To be honest this feels way too easy, so if I am doing something wrong here please feel free to let me know.



blog comments powered by Disqus

All work is original and copyright 2014 by Ash White, with the exception of a handful of free third-party libraries, including the Scriptaculous JavaScript framework, Lightbox image overlay, Google Font Directory, Google Code Prettify, and Eric Meyer's CSS Reset.