How to customize markdown link syntax?

On my blog I have a lot of links on other sites. But it's good practice to use rel="nofollow"
if you add a link on untrusted site. Since I write articles in markdown, I find a way to customize
markdown's parser behevioure to allow this extra attributes for html <a> tags.

Idea

The idea is deadly simple -- just loop through all links, and if it is external one,
add rel="nofollow" target="_blank". Which one is external? You can decide it for yourself.
For example, change syntax by adding ! before URLs and check for that
([1]:!http://my-site.com/article1) and so on. My variant is below.

Link is external, if it is not relative/local :) So I do nothing if href:

starts with / (relative links)

starts with # (anchors links)

In result I have at least two ways to do that.

Method #1 (php only)

If you use some flatfile CMS, like Pico or Phile or anything else,
it's a good practice to write a plugin. Since it's easy to realize with clean php, let's do it.

Code it

My resulting plugin for PhileCMS is on github, and here is some demo-code:

Prons

+ Need not to edit cms/parser core

Cons

- `saveHTML()` method will complement your code to *correct* html, with DOCTYPE, all closed tags and so on. Is it desired behaviour for you?
- If you use not-latin text, you should encode it explicitly into html-enteties and then back. If you use some html-code examples encoded into 'html-enteties', they will become back just html

Method #2 (edit php-markdown parser)

If you cannot write a plugin or cons of method#1 is critical for you, let's do it deeper and simpler
-- during parsing .md and generating html-code.

Code it

If you look at php-markdown library
(if you use another markdown-parser -- idea is the same):

There are two functions:

_doAnchors_reference_callback($matches)

_doAnchors_inline_callback($matches)

for links-reference and inline-links respectively.

NOTE: actually, there are 4 functins, 2 for php-markdown and 2 for php-markdownExtra. Edit the one you are using.