How to parse Markdown in PHP?

被刻印的时光 ゝ 提交于 2019-11-29 21:23:40

You should have a look at Parsedown.

It parses Markdown text the way people do. First, it divides texts into lines. Then it looks at how these lines start and relate to each other. Finally, it looks for special characters to identify inline elements.

There is PHP Markdown Extra that seems to be popular, you could start by looking at its source.

Also, there is an object-oriented implementation of Markdown which is faster: markdown-oo-php

Ciconia - A New Markdown Parser for PHP is a good one I found.

You just need 3 things to do :

1.Install Ciconia and parse file according to the document.
2. Add corresponding css theme to make it nice, like github markdown style or here.
3. Add syntax highlighting javascript, like google Javascript code prettifier.

Then everything will look pretty good.

If you want a complete example, here is my working demo for github style markdown:

<?php
header("Content-Type: text/html;charset=utf-8");
require 'vendor/autoload.php';
use Ciconia\Ciconia;
use Ciconia\Extension\Gfm;

$ciconia = new Ciconia();
$ciconia->addExtension(new Gfm\FencedCodeBlockExtension());
$ciconia->addExtension(new Gfm\TaskListExtension());
$ciconia->addExtension(new Gfm\InlineStyleExtension());
$ciconia->addExtension(new Gfm\WhiteSpaceExtension());
$ciconia->addExtension(new Gfm\TableExtension());
$ciconia->addExtension(new Gfm\UrlAutoLinkExtension());
$contents = file_get_contents('Readme.md');
$html = $ciconia->render($contents);
?>
<!DOCTYPE html>
<html>
    <head>
        <title>Excel to Lua table - Readme</title>
        <script src="https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js"></script>
        <link rel="stylesheet" href="./github-markdown.css">
        <style>
            .markdown-body {
                box-sizing: border-box;
                min-width: 200px;
                max-width: 980px;
                margin: 0 auto;
                padding: 45px;
            }
        </style>
    </head>
    <body>
        <article class="markdown-body">
        <?php
            # Put HTML content in the document
            echo $html;
        ?>
        </article>
    </body>
</html>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!