美文网首页
使用PHP编译Markdown成为HTML代码的基本思路

使用PHP编译Markdown成为HTML代码的基本思路

作者: Separes | 来源:发表于2017-02-13 13:38 被阅读491次

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);
}

相关文章

网友评论

      本文标题:使用PHP编译Markdown成为HTML代码的基本思路

      本文链接:https://www.haomeiwen.com/subject/zeozittx.html