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

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( "\"{$escaped}\"" ); },
$text );

4.添加脚注:

$html .= '

    '; $index = 1; while ($val = array_shift($this->_footnotes)) { if (is_string($val)) { $val .= " "; } else { $val[count($val) - 1] .= " "; $val = count($val) > 1 ? $this->parse(implode("\n", $val)) : $this->parseInline($val[0]); } $html .= "
  1. {$val}
  2. "; $index ++; } $html .= '
';

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代码的基本思路)