Markdown in PHP

HTML isn’t exactly easy for ordinary people to comprehend and use correctly, and allowing it’s use in web forms then entails measures to be taken to prevent malicious code from being inserted.

The infamous John Gruber came up with Markdown, with the help of Aaron Swartz, and whether they intended it to be or not, they came up with the solution to our problem. Using Markdown formatting, you can make text italics by putting an *asterisk* on either side, or bold by using **two.** Blockquotes are as simple as putting a “>” before a paragraph of text. Links are a little more complicated, but they’re easier to do than with straight HTML for the average user.

Markdown is a nifty solution for allowing users of a website to format their input, and it’s gained a good measure of popularity. Reddit is one site that makes use of it for it’s comment forms.

Markdown-enabling a website isn’t too hard for someone with a bit of coding experience. You first need to find an implementation for the language of your choice, unless you want to write your own. Daring Fireball has a Perl implementation right on the Markdown homepage, but what if you’re like me and prefer PHP? Download a copy of PHP Markdown. The script functions like an ordinary PHP library, or as a WordPress plugin, enabling you to use Markdown in comments and the Post Editor.

Using Markdown in your own PHP script is as simple as including markdown.php and passing any Markdown-formatted text through a function to convert it to straight HTML.

include_once "markdown.php";
$my_html = Markdown($my_text);

I would also recommend additionally using the strip_tags PHP function to first remove any HTML tags someone may have put in.

Or you could use the WMD Editor, which applies a JavaScript formatting bar to an input form, allowing the contents to be formatted with Markdown. It then spits out full HTML for the form when it is submitted.