Skip to content

Instantly share code, notes, and snippets.

@bhaskarkc
Created January 14, 2021 07:15
Show Gist options
  • Save bhaskarkc/07c40eb398abbe6977fc04da4fe8fd73 to your computer and use it in GitHub Desktop.
Save bhaskarkc/07c40eb398abbe6977fc04da4fe8fd73 to your computer and use it in GitHub Desktop.
PHP script to parse markdown for headers
<?php
/*
Let's write a simple markdown parser function that will take in a single line of markdown and be translated into the appropriate HTML. To keep it simple, we'll support only one feature of markdown in atx syntax: headers.
Headers are designated by (1-6) hashes followed by a space, followed by text. The number of hashes determines the header level of the HTML output.
Examples
# Header will become <h1>Header</h1>
## Header will become <h2>Header</h2>
###### Header will become <h6>Header</h6>
*/
/**
* Header markdown to HTML markup
*
* @param string $markdown
* @return string
*/
function markdown_parser($markdown)
{
$markup = preg_replace_callback(
'/^(#+)(.+?)\n/',
function ($matches) use ($markdown) {
// bail if regex does not catches anything
if ($matches[1] == "") {
return trim($markdown);
}
// if there is no space after the markdown "#"s reject it.
if (!preg_match('/\s/', $matches[2])) {
return "#" . $matches[2];
}
$hash_count = strlen($matches[1]);
// Bail if hash count is not in range of 1-6.
if (! in_array($hash_count, range(1, 6), true)) {
return trim($markdown);
}
return html_entity_decode("<h$hash_count>" . trim($matches[2]) . "</h$hash_count>");
},
// Adding "\n" to fit our regex.
ltrim($markdown) . "\n"
);
// final cleanup
return trim(preg_replace('~[\r\n]+~', ' ', $markup));
}
@bhaskarkc
Copy link
Author

echo markdown_parser('Behind # The Scenes');
echo PHP_EOL;
echo markdown_parser('# The Scenes');
echo PHP_EOL;
echo markdown_parser("#invalid");
echo PHP_EOL;
echo markdown_parser("##invalid");
echo PHP_EOL;
echo markdown_parser("## header");
echo PHP_EOL;
echo markdown_parser("### header");
echo PHP_EOL;
echo markdown_parser("#### header");
echo PHP_EOL;
echo markdown_parser("## The Scenes");

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment