您看到的 HTML 只是一个预览,因此将其存储在数据库中并不是一个好主意,因为您在尝试编辑时会遇到问题。存储两个版本(markdown 和 HTML)也不是一个好主意,因为 HTML 只是一种解释,您将遇到编辑和保持两个版本同步的相同问题。
所以最好的办法是将markdown存储在数据库中,然后在显示之前将其转换为服务器端。
为此,您可以使用PHP Markdown 。然而,这并不是您在 javascript 端看到的 100% 完美转换,可能需要一些调整。
Stack Exchange 网络使用的版本是 C# 实现,并且应该有一个 python 实现,您下载的 wmd 版本是您拥有的。
我调整的一件事是新行的呈现方式,所以我在 markdown.php 中更改了这一点,以将一些新行转换为<br>
从我拥有的版本中的第 626 行开始:
var $span_gamut = array(
#
# These are all the transformations that occur *within* block-level
# tags like paragraphs, headers, and list items.
#
# Process character escapes, code spans, and inline HTML
# in one shot.
"parseSpan" => -30,
# Process anchor and image tags. Images must come first,
# because ![foo][f] looks like an anchor.
"doImages" => 10,
"doAnchors" => 20,
# Make links out of things like `<http://example.com/>`
# Must come after doAnchors, because you can use < and >
# delimiters in inline links like [this](<url>).
"doAutoLinks" => 30,
"encodeAmpsAndAngles" => 40,
"doItalicsAndBold" => 50,
"doHardBreaks" => 60,
"doNewLines" => 70,
);
function runSpanGamut($text) {
#
# Run span gamut tranformations.
#
foreach ($this->span_gamut as $method => $priority) {
$text = $this->$method($text);
}
return $text;
}
function doNewLines($text) {
return nl2br($text);
}