DEV Community

Jitendra
Jitendra

Posted on

4 years ago I challenged myself to write smallest and fastest markdown parser

Four years ago I challenged myself to write the smallest and fastest markdown to html parser and in a matter of days that got real. Although it was not complete implementation of all markdown specs it still was usable for many cases.

And I named it htmlup! Packed in one single file, one single class and one single method it was less than 220 sloc.

GitHub logo adhocore / htmlup

Light and fast markdown parser, that parses markdown in a way human does

adhocore/htmlup

Latest Version Travis Build Scrutinizer CI Codecov branch StyleCI Software License Donate 15 Donate 25 Donate 50 Tweet

htmlup is ultra lightweight and uber speedy markdown to html parser written in PHP Concept - it splits the markdown into lines and parses to markup one by one, finally applies markdown syntaxes on the markup It supports most of the markdown as in specs.

installation

Run composer require adhocore/htmlup

usage

<?php

use Ahc\HtmlUp;

// require '/path/to/vendor/autoload.php';

// Defaults to 4 space indentation.
echo new Ahc\HtmlUp($markdownText);

// Force 2 space indentation.
echo new HtmlUp($markdownText, 2);

// Also possible:
echo (new Htmlup)->parse($markdownText);
Enter fullscreen mode Exit fullscreen mode

features

nesting

It provides limited support to deep nested elements, supported items are:

  • lists inside lists
  • blockquotes inside blockcodes
  • lists inside blockquotes

raw html

you can throw in your raw html but with a blank line at start and end to delimit the block at like…

You can check the initial working version here

Although the current version is a bit verbose, it still carries the same core concept of parsing:

  1. split the markdown into lines and parse one by one as a human would do
  2. apply block element rules where applicable to get html
  3. apply any span element rules finally

Bonus: It supports table syntax too :)

PS: Before you ask, I know the shortcomings of it and I wouldnt recommend using it in anything serious.

If it inspires you to think bigger problems in small and most basic perspective, or if it encourages you to implement a port in different platform, that would be great.

Thanks for reading! :)

Top comments (1)

Collapse
 
ben profile image
Ben Halpern

Wow, very cool!