Monday, February 20, 2012

PHP Markdown

This snippet of code transforms a markdown string of text into the desired HTML output.
It is the same basic style of formatting that sites like github and Google+ do.
You can easily customize the inputs/outputs of the HTML code that it transforms.



<?
function markDown($str){
//Tag like markdown, ordered by precedence.
//This is the only thing you really need to configure.
//It's a regular expression (without delimiters) as the key and the desired output as the value.
$markdownSet = array(
"\_\*(.*)\*_" => " <b><i>$2</i></b> ",
"\*_(.*)_\*" => " <b><i>$2</i></b> ",
"_(.*)_" => " <i>$2</i> ",
"\*(.*)\*" => " <b>$2</b> ",
"\#\#\#(.*)\#\#\#" => " <h3>$2</h3> ",
"\#\#(.*)\#\#" => " <h2>$2</h2> ",
"\#(.*)\#" => " <h1>$2</h1> "
);
//Strip out the HTML tags, replace them with text
$str = preg_replace('/</','&lt;',$str);
$str = preg_replace('/>/','&gt;',$str);
//Just to make sure they're all gone.
$str = strip_tags($str);
foreach($markdownSet as $match => $result){
$str = preg_replace("/([[:space:]]|\n|^)".$match."([[:space:]]|\n|$)/U","$1".$result."$3",$str);
}
//Make links into links
$str = preg_replace("/http([s]?):\/\/([^\ \)\n$]*)/i","<a href='\\0' rel='nofollow'>\\0</a>",$str);
//Make Newlines into breaks
$str = nl2br($str);
return $str;
}
?>
view raw markDown.php hosted with ❤ by GitHub

No comments:

Post a Comment