New Lines to Paragraphs

Originally released on October 15th, 2002.


By far the most popular code in the site, and has been widely adapted in different projects. Basically it takes PHP’s nl2br function to the logical next step and converts double line breaks to paragraphs where applicable, does line breaks as before, and best of all it’s aware of block-level HTML tags so it won’t mess up your page.


Call this function on the text you want to convert. Think of this code like nl2br on steroids. This is basically a cross-platform set of regular expressions that takes text formatted only by newlines and transforms it into text properly marked up with paragraph and line break tags. The line break part can also be turned off if you want.

To call this function simply use autop($text) in your code somewhere, or autop($text, 0) if you’d like to use it without the line break functionality enabled. It will not echo out the text by itself so you can either assign the parsed text to a variable or echo it out yourself.

The new “extended” version offers smarter paragraphs and breaks that are mindful of block-level HTML tags. If you have legacy content with these tags, or you would just like to be able to drop a tag in there every now and then, try that one out.

Update: The newest and most debugged version of this function can be found in the WordPress source code, third function down. (Here’s a plain-text link.)