rectanglicle

the personal website of ash m. white

05
Feb
2010

Convert Plain-Text Writing Into HTML Paragraphs

Filed under: Tips & Tricks

Tagged: php, newline, paragraph, carriage return

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.

Comments

There are no comments yet

Leave a Comment

I am a software developer and designer in Athens, Georgia. I'm passionate about web development, graphic design, and web standards. I am currently enrolled in the University of Georgia Master of Internet Technology program. More...

@ashwhite

Dear @charlesproxy, You're amazing. Love, Ash

about 15 hours ago

Thanks to @johnallsopp for the very inspiring talk tonight about HTML5 and the future of web technology.

about 3 days ago

@Stormink Other bad changes aside, CDs are not analog. If the icon had started as a vinyl record, that would be a totally different story.

about 3 days ago

@koefod You're on a Mac, right? You should give this a try: http://agilewebsolutions.com/products/1Password

about 3 days ago

When method names include the word "kludge," it's a bad sign.

about 4 days ago