Skip to content

Instantly share code, notes, and snippets.

@miwebguy
Created December 23, 2025 20:37
Show Gist options
  • Select an option

  • Save miwebguy/e2008f2aab49a1335fd9cc36451119a9 to your computer and use it in GitHub Desktop.

Select an option

Save miwebguy/e2008f2aab49a1335fd9cc36451119a9 to your computer and use it in GitHub Desktop.
PHP Simple Markdown Function
<?php
// source inspiration unknown
function markdownToHtml($markdown) {
// Convert headers
$markdown = preg_replace('/^###### (.*)$/m', '<h6>$1</h6>', $markdown);
$markdown = preg_replace('/^##### (.*)$/m', '<h5>$1</h5>', $markdown);
$markdown = preg_replace('/^#### (.*)$/m', '<h4>$1</h4>', $markdown);
$markdown = preg_replace('/^### (.*)$/m', '<h3>$1</h3>', $markdown);
$markdown = preg_replace('/^## (.*)$/m', '<h2>$1</h2>', $markdown);
$markdown = preg_replace('/^# (.*)$/m', '<h1>$1</h1>', $markdown);
// Convert bold text
$markdown = preg_replace('/\*\*(.+?)\*\*/', '<strong>\1</strong>', $markdown);
// Convert italic text
$markdown = preg_replace('/\*(.+?)\*/', '<em>\1</em>', $markdown);
// Convert links
$markdown = preg_replace('/\[(.+?)\]\((.+?)\)/', '<a href="\2">\1</a>', $markdown);
// Convert unordered lists
$markdown = preg_replace('/^\s*-\s+(.+)$/m', '<li>\1</li>', $markdown);
$markdown = preg_replace('/(<li>.*<\/li>)/s', '<ul>\1</ul>', $markdown);
// Convert tables
$markdown = preg_replace_callback(
'/^\|(.+)\|\n\|(?:-+\|)+\n((?:\|.+\|\n)+)/m',
function ($matches) {
$headers = explode('|', trim($matches[1]));
$rows = explode("\n", trim($matches[2]));
$thead = '<thead><tr>';
foreach ($headers as $header) {
$thead .= '<th>' . trim($header) . '</th>';
}
$thead .= '</tr></thead>';
$tbody = '<tbody>';
foreach ($rows as $row) {
$tbody .= '<tr>';
$cells = explode('|', trim($row));
foreach ($cells as $cell) {
$tbody .= '<td>' . trim($cell) . '</td>';
}
$tbody .= '</tr>';
}
$tbody .= '</tbody>';
return '<table>' . $thead . $tbody . '</table>';
},
$markdown
);
// Convert line breaks
// $markdown = nl2br($markdown);
return $markdown;
}
// Example usage
$markdown = <<<EOD
# Header 1
## Header 2
**Bold Text**
*Italic Text*
[Link](https://example.com)
- Item 1
- Item 2
### Header 3
| Top | CODE | Model | Capacity | Power | Engine |
|-----|------|-------|----------|-------|--------|
| | AF30 | MAP1F1A15LV | 3000 | LP - G/LP | K21 |
| | AF35 | MAP1F1A18LV | 3500 | LP - G/LP | K21 |
| * | AF50 | MAP1F2A25LV | 5000 | LP - G/LP | K21 |
| * | CF30 | MCP1F1A15LV | 3000 | LP - G/LP | |
| | CF35 | | 3500 | LP - G/LP | EK21 |
| | CF40 | | 4000 | LP - G/LP | EK21 |
| | CFS40 | | 4000 | LP - G/LP | EK21 |
| | CFU40 | | 4000 | LP - G/LP | EK21 |
| * | CF50 | MCP1F2A25LV | 5000 | LP - G/LP | EK21 |
| | CFU50 || 5000 | LP - G/LP | EK21 |
EOD;
echo markdownToHtml($markdown);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment