PHP怎么解析Markdown

wen PHP项目 1

本文目录导读:

PHP怎么解析Markdown

  1. 使用第三方库(推荐)
  2. 使用PHP自带函数(简单场景)
  3. 完整示例:Markdown到HTML转换器
  4. 安全注意事项
  5. 性能优化建议
  6. 选择建议

在PHP中解析Markdown,主要有以下几种方式:

使用第三方库(推荐)

Parsedown(最流行)

// 安装:composer require erusev/parsedown
require 'vendor/autoload.php';
$parsedown = new Parsedown();
$markdown = "# 标题\n\n这是**加粗**文本";
$html = $parsedown->text($markdown);
echo $html;

Parsedown Extra(支持更多特性)

// 安装:composer require erusev/parsedown-extra
require 'vendor/autoload.php';
$parsedown = new ParsedownExtra();
$markdown = "| 列1 | 列2 |\n|-----|-----|\n| 内容 | 内容 |";
$html = $parsedown->text($markdown);
echo $html;

CommonMark(标准实现)

// 安装:composer require league/commonmark
require 'vendor/autoload.php';
$converter = new League\CommonMark\CommonMarkConverter();
$markdown = "# 标题";
$html = $converter->convertToHtml($markdown);
echo $html;

使用PHP自带函数(简单场景)

function simpleMarkdown($text) {
    // 转义HTML
    $text = htmlspecialchars($text);
    // 标题
    $text = preg_replace('/^### (.*)$/m', '<h3>$1</h3>', $text);
    $text = preg_replace('/^## (.*)$/m', '<h2>$1</h2>', $text);
    $text = preg_replace('/^# (.*)$/m', '<h1>$1</h1>', $text);
    // 加粗
    $text = preg_replace('/\*\*(.*?)\*\*/', '<strong>$1</strong>', $text);
    // 斜体
    $text = preg_replace('/\*(.*?)\*/', '<em>$1</em>', $text);
    // 链接
    $text = preg_replace('/\[(.*?)\]\((.*?)\)/', '<a href="$2">$1</a>', $text);
    // 换行
    $text = nl2br($text);
    return $text;
}

完整示例:Markdown到HTML转换器

class MarkdownParser {
    private $content;
    public function __construct($markdown) {
        $this->content = $markdown;
    }
    public function parse() {
        $this->parseHeaders();
        $this->parseBold();
        $this->parseItalic();
        $this->parseLinks();
        $this->parseLists();
        $this->parseCodeBlocks();
        $this->parseParagraphs();
        return $this->content;
    }
    private function parseHeaders() {
        $this->content = preg_replace('/^### (.*)$/m', '<h3>$1</h3>', $this->content);
        $this->content = preg_replace('/^## (.*)$/m', '<h2>$1</h2>', $this->content);
        $this->content = preg_replace('/^# (.*)$/m', '<h1>$1</h1>', $this->content);
    }
    private function parseBold() {
        $this->content = preg_replace('/\*\*(.*?)\*\*/', '<strong>$1</strong>', $this->content);
    }
    private function parseItalic() {
        $this->content = preg_replace('/\*(.*?)\*/', '<em>$1</em>', $this->content);
    }
    private function parseLinks() {
        $this->content = preg_replace('/\[(.*?)\]\((.*?)\)/', '<a href="$2">$1</a>', $this->content);
    }
    private function parseLists() {
        // 无序列表
        $this->content = preg_replace('/^- (.*)$/m', '<li>$1</li>', $this->content);
        // 有序列表
        $this->content = preg_replace('/^\d+\. (.*)$/m', '<li>$1</li>', $this->content);
    }
    private function parseCodeBlocks() {
        $this->content = preg_replace('/```(\w*)?\n(.*?)```/s', 
            '<pre><code class="language-$1">$2</code></pre>', $this->content);
    }
    private function parseParagraphs() {
        $parts = explode("\n\n", $this->content);
        foreach ($parts as &$part) {
            if (!preg_match('/^<h[1-3]>/', $part) && 
                !preg_match('/^<pre>/', $part)) {
                $part = '<p>' . $part . '</p>';
            }
        }
        $this->content = implode("\n", $parts);
    }
}
// 使用示例
$parser = new MarkdownParser("# 我的标题\n\n这是**加粗**文本和[链接](https://example.com)");
echo $parser->parse();

安全注意事项

// 使用Parsedown时启用安全模式
$parsedown = new Parsedown();
$parsedown->setSafeMode(true); // 禁用HTML标签
$html = $parsedown->text($markdown);
// 或者手动清理
$html = strip_tags($html, '<p><a><strong><em><h1><h2><h3><ul><ol><li><code><pre><blockquote>');

性能优化建议

// 使用缓存
function parseMarkdownWithCache($markdown) {
    $cacheKey = md5($markdown);
    $cacheFile = '/tmp/markdown_' . $cacheKey . '.html';
    if (file_exists($cacheFile)) {
        return file_get_contents($cacheFile);
    }
    $parser = new Parsedown();
    $html = $parser->text($markdown);
    file_put_contents($cacheFile, $html);
    return $html;
}

选择建议

  • 简单需求:使用Parsedown(轻量、快速)
  • 标准功能:使用CommonMark(最规范)
  • 表格支持:使用Parsedown Extra
  • 完整框架:使用Laravel的Markdown集成或Thunderer\Shortcode

推荐使用Parsedown,因为它既简单又功能完整,且维护活跃。

抱歉,评论功能暂时关闭!