Markdown to HTML Converter — PHP source
Render Markdown into clean, escaped HTML: headings, lists, links, images, code blocks and quotes. Every input is escaped first, so the output is always safe markup. Runs locally with a shareable link.
This is the PHP implementation — the same logic the interactive tool runs, in a shareable, citable form.
<?php
// markdown-to-html — escape-first CommonMark subset → HTML renderer. PHP port
// (canonical TS: src/lib/markdown-to-html.ts; Go twin: cli/markdown-to-html).
// Hand-rolled CommonMark SUBSET — everything is HTML-escaped before the inline
// rules run (raw HTML never passes through; security first), via the shared
// five-char escaper inlined here (`&` first so the entities we emit are never
// re-escaped). Supported blocks: #-headings (1-6), --- /***/ ___ rules, ```
// fenced code (markdown inert inside), > blockquotes (recursive), - * +
// unordered lists, N. ordered lists (source numbers stripped), paragraphs
// (soft line breaks joined with \n). Inline precedence: code spans first
// (placeholder-protected), then images, links, bold, italic, strikethrough —
// non-greedy pairs. Not supported (by design, documented): raw HTML, tables,
// setext headings, nested lists, footnotes, autolinks. Empty or whitespace-only
// input is NOT an error — the tool shows nothing. Never throws — errors travel
// in the result array.
const MARKDOWN_TO_HTML_HEADING = '/^(#{1,6}) (.*)$/';
const MARKDOWN_TO_HTML_HR = '/^(---+|\*\*\*+|___+)\s*$/';
const MARKDOWN_TO_HTML_UL = '/^[-*+] /';
const MARKDOWN_TO_HTML_OL = '/^\d+\. /';
const MARKDOWN_TO_HTML_CODE_SPAN = '/`([^`]+)`/';
const MARKDOWN_TO_HTML_IMAGE = '/!\[([^\]]*)\]\(([^)\s]+)\)/';
const MARKDOWN_TO_HTML_LINK = '/\[([^\]]+)\]\(([^)\s]+)\)/';
/** Five-char escaper (from src/lib/htmlEntities.ts); `&` is replaced first so
* the entities we emit are never re-escaped. */
function markdown_to_html_encode_html(string $text): string
{
return str_replace(
['&', '<', '>', '\'', '"'],
['&', '<', '>', ''', '"'],
$text
);
}
/** Inline pass: code spans first (placeholder-protected), then images, links,
* bold, italic, strikethrough — non-greedy pairs. */
function markdown_to_html_render_inline(string $s): string
{
$codes = [];
$text = preg_replace_callback(MARKDOWN_TO_HTML_CODE_SPAN, function ($m) use (&$codes) {
$codes[] = '<code>' . markdown_to_html_encode_html($m[1]) . '</code>';
return "\x00" . (count($codes) - 1) . "\x00";
}, $s);
$text = markdown_to_html_encode_html($text);
$text = preg_replace_callback(
MARKDOWN_TO_HTML_IMAGE,
fn ($m) => '<img src="' . $m[2] . '" alt="' . $m[1] . '">',
$text
);
$text = preg_replace_callback(
MARKDOWN_TO_HTML_LINK,
fn ($m) => '<a href="' . $m[2] . '">' . $m[1] . '</a>',
$text
);
$text = preg_replace_callback('/\*\*([^*]+)\*\*/', fn ($m) => "<strong>{$m[1]}</strong>", $text);
$text = preg_replace_callback('/__([^_]+)__/', fn ($m) => "<strong>{$m[1]}</strong>", $text);
$text = preg_replace_callback('/\*([^*]+)\*/', fn ($m) => "<em>{$m[1]}</em>", $text);
$text = preg_replace_callback('/_([^_]+)_/', fn ($m) => "<em>{$m[1]}</em>", $text);
$text = preg_replace_callback('/~~([^~]+)~~/', fn ($m) => "<del>{$m[1]}</del>", $text);
return preg_replace_callback('/\x00(\d+)\x00/', fn ($m) => $codes[(int) $m[1]], $text);
}
/** True when a line STARTS a new block — the paragraph terminator. Any new
* block type must register here and in the render_block dispatch below. */
function markdown_to_html_is_block_start(string $line): bool
{
return preg_match(MARKDOWN_TO_HTML_HEADING, $line)
|| preg_match(MARKDOWN_TO_HTML_HR, $line)
|| str_starts_with($line, '```')
|| str_starts_with($line, '> ')
|| preg_match(MARKDOWN_TO_HTML_UL, $line)
|| preg_match(MARKDOWN_TO_HTML_OL, $line);
}
/** Render consecutive lines (one blank-line-separated chunk). */
function markdown_to_html_render_block(array $lines, array &$out): void
{
$i = 0;
while ($i < count($lines)) {
$line = $lines[$i];
if (preg_match(MARKDOWN_TO_HTML_HEADING, $line, $heading)) {
$level = strlen($heading[1]);
$out[] = "<h{$level}>" . markdown_to_html_render_inline(trim($heading[2])) . "</h{$level}>";
$i++;
continue;
}
if (preg_match(MARKDOWN_TO_HTML_HR, $line)) {
$out[] = '<hr>';
$i++;
continue;
}
if (str_starts_with($line, '```')) {
$lang = trim(substr($line, 3));
$body = [];
$i++;
while ($i < count($lines) && !str_starts_with($lines[$i], '```')) {
$body[] = $lines[$i];
$i++;
}
$i++; // past the closing fence (or past the end of an unclosed fence)
$cls = $lang === '' ? '' : ' class="language-' . markdown_to_html_encode_html($lang) . '"';
$out[] = '<pre><code' . $cls . '>' . markdown_to_html_encode_html(implode("\n", $body)) . '</code></pre>';
continue;
}
if (str_starts_with($line, '> ')) {
$quoted = [];
while ($i < count($lines) && str_starts_with($lines[$i], '> ')) {
$quoted[] = substr($lines[$i], 2);
$i++;
}
$inner = [];
markdown_to_html_render_block($quoted, $inner);
$out[] = "<blockquote>\n" . implode("\n", $inner) . "\n</blockquote>";
continue;
}
if (preg_match(MARKDOWN_TO_HTML_UL, $line)) {
$items = [];
while ($i < count($lines) && preg_match(MARKDOWN_TO_HTML_UL, $lines[$i])) {
$items[] = '<li>' . markdown_to_html_render_inline(substr($lines[$i], 2)) . '</li>';
$i++;
}
$out[] = "<ul>\n" . implode("\n", $items) . "\n</ul>";
continue;
}
if (preg_match(MARKDOWN_TO_HTML_OL, $line)) {
$items = [];
while ($i < count($lines) && preg_match(MARKDOWN_TO_HTML_OL, $lines[$i])) {
preg_match(MARKDOWN_TO_HTML_OL, $lines[$i], $om);
$items[] = '<li>' . markdown_to_html_render_inline(substr($lines[$i], strlen($om[0]))) . '</li>';
$i++;
}
$out[] = "<ol>\n" . implode("\n", $items) . "\n</ol>";
continue;
}
$para = [];
while ($i < count($lines) && !markdown_to_html_is_block_start($lines[$i])) {
$para[] = markdown_to_html_render_inline(trim($lines[$i]));
$i++;
}
$out[] = '<p>' . implode("\n", $para) . '</p>';
}
}
/**
* Convert the supported Markdown subset to HTML. Never fails.
* @return array{output: string, error: null}
*/
function markdown_to_html(string $raw): array
{
$text = trim((string) preg_replace('/\r\n?/', "\n", $raw));
if ($text === '') return ['output' => '', 'error' => null]; // NOT an error
$out = [];
foreach (preg_split("/\n{2,}/", $text) as $block) {
$lines = array_values(array_filter(explode("\n", $block), fn ($l) => trim($l) !== ''));
markdown_to_html_render_block($lines, $out);
}
return ['output' => implode("\n", $out), 'error' => null];
}
// Example:
// markdown_to_html('## Hello *world*')['output']
// → '<h2>Hello <em>world</em></h2>'
// markdown_to_html("```js\nconst x = 1; // <b>\n```")['output']
// → '<pre><code class="language-js">const x = 1; // <b></code></pre>'
// markdown_to_html('<script>alert(1)</script>')['output']
// → '<p><script>alert(1)</script></p>'
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →