|
2
|
1 <?php
|
|
|
2
|
|
|
3 namespace Libraries;
|
|
|
4
|
|
|
5 class MarkdownParser
|
|
|
6 {
|
|
|
7 public static function toHtml(string $markdown): string
|
|
|
8 {
|
|
|
9 $code_block_pattern = '/```([a-z]+)\s+(.*?)\s+```/si';
|
|
|
10 $inline_code_pattern = '/`\s*(.*?)\s*`/si';
|
|
|
11 $matches = [];
|
|
|
12
|
|
|
13 preg_match_all($code_block_pattern, $markdown, $matches, PREG_SET_ORDER);
|
|
|
14 $code_blocks = [];
|
|
|
15 foreach ($matches as $index => $match) {
|
|
|
16 $code_blocks[] = [
|
|
|
17 'language' => $match[1],
|
|
|
18 'code' => $match[2],
|
|
|
19 ];
|
|
|
20 }
|
|
|
21
|
|
|
22 foreach ($matches as $index => $match) {
|
|
|
23 $markdown = preg_replace('/'.preg_quote($match[0], '/').'/', '[CODE_BLOCK_'.$index.']', $markdown, 1);
|
|
|
24 }
|
|
|
25
|
|
|
26 preg_match_all($inline_code_pattern, $markdown, $matches, PREG_SET_ORDER);
|
|
|
27 $inline_code = [];
|
|
|
28 foreach ($matches as $index => $match) {
|
|
|
29 $inline_code[] = [
|
|
|
30 'code' => $match[1],
|
|
|
31 ];
|
|
|
32 }
|
|
|
33
|
|
|
34 foreach ($matches as $index => $match) {
|
|
|
35 $markdown = preg_replace('/'.preg_quote($match[0], '/').'/', '[INLINE_CODE_'.$index.']', $markdown, 1);
|
|
|
36 }
|
|
|
37
|
|
|
38 $markdown = preg_replace('/`(.+?)`/', '<code>$1</code>', $markdown);
|
|
|
39 $markdown = preg_replace('/\#{6}\s(.+)/', '<h6>$1</h6>', $markdown);
|
|
|
40 $markdown = preg_replace('/\#{5}\s(.+)/', '<h5>$1</h5>', $markdown);
|
|
|
41 $markdown = preg_replace('/\#{4}\s(.+)/', '<h4>$1</h4>', $markdown);
|
|
|
42 $markdown = preg_replace('/\#{3}\s(.+)/', '<h3>$1</h3>', $markdown);
|
|
|
43 $markdown = preg_replace('/\#{2}\s(.+)/', '<h2>$1</h2>', $markdown);
|
|
|
44 $markdown = preg_replace('/\#\s(.+)/', '<h1>$1</h1>', $markdown);
|
|
|
45 $markdown = preg_replace('/\*\*\*(.+?)\*\*\*/', '<strong><em>$1</em></strong>', $markdown);
|
|
|
46 $markdown = preg_replace('/\*\*(.+?)\*\*/', '<strong>$1</strong>', $markdown);
|
|
|
47 $markdown = preg_replace('/\*(.+?)\*/', '<em>$1</em>', $markdown);
|
|
|
48 $markdown = preg_replace('/\[(.+?)\]\((.+?)\)/', '<a href="$2">$1</a>', $markdown);
|
|
|
49 $markdown = preg_replace("/\r\n|\r|\n/", '<br>', $markdown);
|
|
|
50
|
|
|
51 foreach ($code_blocks as $index => $code_block) {
|
|
|
52 $language = $code_block['language'];
|
|
|
53 $language = $language == 'blade' ? 'html' : $language;
|
|
|
54 $code_block['code'] = '<pre><code class="match-braces language-'.$language.'">'.htmlentities($code_block['code']).'</code></pre>';
|
|
|
55 $markdown = str_replace('[CODE_BLOCK_'.$index.']', $code_block['code'], $markdown);
|
|
|
56 }
|
|
|
57
|
|
|
58 foreach ($inline_code as $index => $code) {
|
|
|
59 $code['code'] = '<code>'.htmlentities($code['code']).'</code>';
|
|
|
60 $markdown = str_replace('[INLINE_CODE_'.$index.']', $code['code'], $markdown);
|
|
|
61 }
|
|
|
62
|
|
|
63 return $markdown;
|
|
|
64 }
|
|
|
65 }
|