Last active
October 25, 2019 09:19
-
-
Save hadaytullah/0007fcfdae4c6af39be30817ccee2c0a to your computer and use it in GitHub Desktop.
Convert header h1-h6 markdown in php to html
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<? 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