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

@gwakie I use NetNewsWire for RSS (syncs with Reader, but with a much better interface). Can't help you with Wave.

about 1 day ago

Working with JDBC. Surprisingly, I don't want to murder it this time.

about 2 days ago

@peachmactweet Got any of the new trackpads yet? =P

about 2 days ago

Web Inspector > Firebug. There, I said it.

about 3 days ago

@notasausage Athens is amazing. There's a bunch of great houses for sale here.

about 6 days ago