使用PHP編譯Markdown成為HTML程式碼的基本思路

weixin_33860722發表於2017-02-13

Github Reference:傳送門

1.從前端獲得Markdown原始資料:

$s_markdown = $this->input->expectType('p:markdown', 'string', '');

2.將原文中的水平製表符\t替換成空格,去除換行符\r:

private function initText($text) { $text = str_replace(array("\t", "\r"), array(' ', ''), $text); return $text; }

3.處理所有的Mark符號,轉變為HTML標籤(例):

$text = preg_replace_callback( "/!\[((?:[^\]]|\\\\\]|\\\\\[)*?)\]\(((?:[^\)]|\\\\\)|\\\\\()+?)\)/",
function ($matches) use ($self)
{ $escaped = $self->escapeBracket($matches[1]);
$url = $self->escapeBracket($matches[2]);
$url = $self->cleanUrl($url);
return $self->makeHolder( "<img src=\"{$url}\" alt=\"{$escaped}\" title=\"{$escaped}\">" ); },
$text );

4.新增腳註:

$html .= '<div class="footnotes"><hr><ol>';
$index = 1;
while ($val = array_shift($this->_footnotes))
{
if (is_string($val))
{
$val .= " <a href=\"#fnref-{$index}\" class=\"footnote-backref\"></a>";
}
else
{
$val[count($val) - 1] .= " <a href=\"#fnref-{$index}\" class=\"footnote-backref\"></a>";
$val = count($val) > 1 ? $this->parse(implode("\n", $val)) : $this->parseInline($val[0]);
}
$html .= "<li id=\"fn-{$index}\">{$val}</li>"; $index ++; }
$html .= '</ol></div>';

5.將以上轉換方法宣告為過載函式,遞迴呼叫:

public function makeHtml($text)
{ $text = $this->initText($text);
$html = $this->parse($text);
$html = $this->makeFootnotes($html);
return $this->call('makeHtml', $html);
}

相關文章