OverviewFilesCommitsIssuesDocsReleasesPeers

folio / lib / markdown.php

28 lines · php ref:
<?php
// lib/markdown.php — Minimal markdown-to-HTML parser

function parse_markdown($md) {
    $html = $md;

    // Headings (must be processed before paragraphs)
    $html = preg_replace('/^### (.+)$/m', '<h3>$1</h3>', $html);
    $html = preg_replace('/^## (.+)$/m', '<h2>$1</h2>', $html);
    $html = preg_replace('/^# (.+)$/m', '<h1>$1</h1>', $html);

    // Inline formatting
    $html = preg_replace('/\*\*(.+?)\*\*/', '<strong>$1</strong>', $html);
    $html = preg_replace('/\*(.+?)\*/', '<em>$1</em>', $html);
    $html = preg_replace('/\[([^\]]+)\]\(([^)]+)\)/', '<a href="$2">$1</a>', $html);

    // Paragraphs: split on double newlines
    $html = preg_replace('/\n\n+/', '</p><p>', $html);
    $html = '<p>' . $html . '</p>';

    // Clean up headings wrapped in <p> tags
    $html = preg_replace('/<p>(<h[123]>)/', '$1', $html);
    $html = preg_replace('/(<\/h[123]>)<\/p>/', '$1', $html);
    $html = str_replace('<p></p>', '', $html);

    return $html;
}