New Lines to Paragraphs

Originally released on October 15th, 2002.

Description

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.

Installation/Usage

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.)

5 thoughts on “New Lines to Paragraphs

  1. Fantastic trick. All I did was, get the:

    function wpautop($pee, $br = 1)

    function from the plain-text link and called it like this:

    $bbDesc = autop($bbDesc);

    (Note that I changed the name of it.) The code worked strait away and means now that whenever a user types in new lines or paragraphs they are preserved perfectly. Thanks for the tip, it’ll help loads with my University Demo of my website tomorrow!

  2. Nice Script – I’m very impressed – However in the latest .NET mag where you were interviewed – you said you were a terrible programmer… you lied!

    Keep up the good work!

    Sean 😉

  3. Wow Matt … and “Hey there!” … 2002 … I feel like I’m setting foot in a living museum!

    Very nice of you to have left a paper-trail like this. You did a Good Thing.

    cheers
    and best of ’08 to y’all at ‘mattic
    –bentmre

SHARE YOUR THOUGHTS