From 2e6da53a7cf0d40bbae373f100a40508760d254b Mon Sep 17 00:00:00 2001 From: Henrique Moody Date: Sun, 8 Feb 2015 18:17:19 -0200 Subject: [PATCH] Add "id" attribute to headings --- Parsedown.php | 32 ++++++++++++++++++++++++++++++++ test/data/atx_heading.html | 18 +++++++++++------- test/data/atx_heading.md | 8 ++++++++ 3 files changed, 51 insertions(+), 7 deletions(-) diff --git a/Parsedown.php b/Parsedown.php index 9bdae22..c62590d 100755 --- a/Parsedown.php +++ b/Parsedown.php @@ -19,6 +19,8 @@ class Parsedown const version = '1.5.1'; + private $headingSlugs = array(); + # ~ function text($text) @@ -462,6 +464,33 @@ class Parsedown return $Block; } + protected function slugify($text) + { + $slug = trim($text); + $slug = strtr($slug, ' ', '-'); + $slug = strtolower($slug); + + return preg_replace('/[^a-z0-9_-]/', '', $slug); + } + + protected function getHeadingId($text) + { + $slug = $this->slugify($text); + $attributeId = $slug; + + if (!isset($this->headingSlugs[$slug])) { + $this->headingSlugs[$slug] = 0; + } + + if ($this->headingSlugs[$slug] > 0) { + $attributeId .= '-'.$this->headingSlugs[$slug]; + } + + $this->headingSlugs[$slug]++; + + return $attributeId; + } + # # Header @@ -488,6 +517,9 @@ class Parsedown 'name' => 'h' . min(6, $level), 'text' => $text, 'handler' => 'line', + 'attributes' => array( + 'id' => $this->getHeadingId($text), + ), ), ); diff --git a/test/data/atx_heading.html b/test/data/atx_heading.html index 751f873..3af9d26 100644 --- a/test/data/atx_heading.html +++ b/test/data/atx_heading.html @@ -1,9 +1,13 @@ -

h1

-

h2

-

h3

-

h4

-
h5
-
h6
+

h1

+

h2

+

h3

+

h4

+
h5
+
h6

####### not a heading

-

closed h1

+

closed h1

+

Repeated

+

Repeated

+

Repeated

+

this_is_a_name(boolean $something = true) - Function

#

\ No newline at end of file diff --git a/test/data/atx_heading.md b/test/data/atx_heading.md index ad97b44..1d3decf 100644 --- a/test/data/atx_heading.md +++ b/test/data/atx_heading.md @@ -14,4 +14,12 @@ # closed h1 # +## Repeated + +## Repeated + +## Repeated + +## this_is_a_name(boolean $something = true) - Function + # \ No newline at end of file