Auto named-anchors in markdown

markdown, php, regex

Solution

Seeing as you're already using PHP, you should really take a look at the Markdown Extra implementation. From the MDE docs:

With PHP Markdown Extra, you can set id attribute to headers. You should add the id prefixed by a hash inside curly brackets after the header at the end of the line, like this:

Header 1            {#header1}
========

## Header 2 ##      {#header2}

Then you can create links to different parts of the same document like this:

[Link back to header 1](#header1)

Problem

I am using Markdown in PHP and have written a regex to automatically wrap the text inside if any `<h1>-<h6>` tag with a named-anchor (`<a name="Text">Text</a>`) for linking. Here is the PHP: ``` $text = '<p>This is a</p> <h1>Test</h1> <p>to see if this works </p>'; $regex = '/\<h([0-6]{1})\>(.+)\<\/h[0-6]{1}\>/'; echo preg_replace($regex, '<h$1><a name="$2">$2</a></h$1>', $text); ``` And the result is: ``` <p>This is a</p> <h1><a name="Test">Test</a></h1> <p>to see if this works </p> ``` The important thing here is, Markdown is light-weight and easy on storage space. Manually adding in the named-anchors kind of defeats the purpose of using Markdown altogether. This method works fine for testing purposes, but I would like to know (and here is the question) if there is a better, more language-agnostic, way to accomplish this. NOTE: The client this is for, wants it this way because they feel even the native Markdown syntax may alienate their more "computer-illiterate" users: `# [Text](#Text)`. They simply want to type: `# Text`

Original source