Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Convert header h1-h6 markdown in php to html
<? php
function markdown_parser ($markdown) {
$segments = explode('# ', trim($markdown), 2);
if(count($segments)>1){
//adding back the hash that explode removed, this simplifies the logic below
$segments[0] = $segments[0].'#';
//making sure that all are hashes and nothing else at the start of markdown
$first_array = str_split($segments[0]);
$unique = array_unique($first_array);
// all are hashes and not more than 6
if(count($unique) == 1 and strlen($segments[0]) < 7){
//everything is good, make the html
$header = 'h'.(string)strlen($segments[0]);
return '<'.$header.'>'.trim($segments[1]).'</'.$header.'>';
}
}
return $markdown;
}
class MarkdownParserSolution extends TestCase
{
public function testBasicValidCases() {
$this->assertSame("<h1>header</h1>", markdown_parser("# header"));
$this->assertSame("<h2>smaller header</h2>", markdown_parser("## smaller header"));
}
public function testBasicInvalidCases() {
$this->assertSame("#Invalid", markdown_parser("#Invalid"));
$this->assertSame("dbcdddd# Invalid", markdown_parser("dbcdddd# Invalid"));
$this->assertSame("ddddd# Invalid", markdown_parser("ddddd# Invalid"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment