Quick Snippet: Automatic Link Parsing with Markdown

August 15th, 2012

While writing a web app with the Laravel PHP framework, I needed the ability to allow users to write posts with Markdown. I used an awesome bundle called Sparkdown by Phill Sparks, to handle the heavy lifting. Unfortunately, what it doesn’t do is automatically create hyperlinks from urls. 

All Laravel apps have a library folder, where you can drop classes in, and have them autoloaded for your convenience. I went ahead and created a very simple class with a single function that takes a string argument, which looks for urls that aren’t already Markdown-ready, and wraps the link in angle brackets. With these angle brackets, the Sparkdown bundle will turn them into proper hyperlinks. Here’s my class:

class MD {
	public static function linkify($aString){
		$url_regex = '(http|https|ftp)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}'. 
		'(:[a-zA-Z0-9]*)?\/?([a-zA-Z0-9\-\._\?\,\'\/\\\+&%\$#\=~])*[^\.\,\)\(\s]';
	   // Only replace if it isn't already a Markdown style link
	    return preg_replace(
	        '/' . '(^|[^\[\(<"]\s*)' . '(' . $url_regex . ')' . '/',
	        '$1[$2]($2)',
	        $aString
	    );
	}
}