-
Notifications
You must be signed in to change notification settings - Fork 84
/
TitleIdPreprocessor.php
55 lines (48 loc) · 1.37 KB
/
TitleIdPreprocessor.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<?php
namespace helpers\Markdown;
/**
* Adds autogenerated ID attributes to titles.
*
* E.g. this:
*
* ## Some title
*
* Will be modified to this:
*
* ## Some title {#some-title}
*
* This syntax to add ID attributes is supported by Markdown Extra.
*/
class TitleIdPreprocessor implements MarkdownParserInterface
{
/**
* @var MarkdownParserInterface
*/
private $wrapped;
public function __construct(MarkdownParserInterface $wrapped)
{
$this->wrapped = $wrapped;
}
public function parse($markdown)
{
$markdown = preg_replace_callback('/^#+ +([^\{\n]+)$/m', function (array $matches) {
$title = self::headlineTextToHtmlId($matches[1]);
return sprintf('%s {#%s}', $matches[0], $title);
}, $markdown);
return $this->wrapped->parse($markdown);
}
/**
* @param string $headlineText
* @return string
*/
public static function headlineTextToHtmlId($headlineText)
{
$headlineText = strip_tags($headlineText);
$headlineText = trim($headlineText);
$headlineText = preg_replace('/\s/', '-', $headlineText);
$headlineText = preg_replace('/[^a-zA-Z0-9\-\_]/', '', $headlineText);
$headlineText = preg_replace('/(\-)+/', '-', $headlineText);
$headlineText = strtolower($headlineText);
return $headlineText;
}
}