mirror of
https://github.com/erusev/parsedown.git
synced 2024-09-20 03:51:29 +02:00
Add "id" attribute to headings
This commit is contained in:
parent
65116c3cb0
commit
2e6da53a7c
@ -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),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
|
@ -1,9 +1,13 @@
|
||||
<h1>h1</h1>
|
||||
<h2>h2</h2>
|
||||
<h3>h3</h3>
|
||||
<h4>h4</h4>
|
||||
<h5>h5</h5>
|
||||
<h6>h6</h6>
|
||||
<h1 id="h1">h1</h1>
|
||||
<h2 id="h2">h2</h2>
|
||||
<h3 id="h3">h3</h3>
|
||||
<h4 id="h4">h4</h4>
|
||||
<h5 id="h5">h5</h5>
|
||||
<h6 id="h6">h6</h6>
|
||||
<p>####### not a heading</p>
|
||||
<h1>closed h1</h1>
|
||||
<h1 id="closed-h1">closed h1</h1>
|
||||
<h2 id="repeated">Repeated</h2>
|
||||
<h2 id="repeated-1">Repeated</h2>
|
||||
<h2 id="repeated-2">Repeated</h2>
|
||||
<h2 id="this_is_a_nameboolean-something--true---function">this_is_a_name(boolean $something = true) - Function</h2>
|
||||
<p>#</p>
|
@ -14,4 +14,12 @@
|
||||
|
||||
# closed h1 #
|
||||
|
||||
## Repeated
|
||||
|
||||
## Repeated
|
||||
|
||||
## Repeated
|
||||
|
||||
## this_is_a_name(boolean $something = true) - Function
|
||||
|
||||
#
|
Loading…
Reference in New Issue
Block a user