Skip to content
Advertisement

Failed to markdown parser function in php using regex

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>

My code :

function markdown_parser ($markdown) {
$regex = '/(?:(#+)(.+?)n)|(?:(.+?)ns*=+s*n)/';
$headerText = $markdown."n";
$headerText = preg_replace_callback(
    $regex,
    function($matches){
        if (!preg_match('/s/',$matches[2])) {
            return "#".$matches[2];
        }
        if($matches[1] != ""){
           $h_num = strlen($matches[1]);
           return html_entity_decode("<h$h_num>".trim($matches[2])."</h$h_num>");
        }  
    },
    $headerText
);
return $headerText;
}

its not working as failed test case :

Failed asserting that two strings are identical.
Expected: Behind # The Scenes
Actual  : Behind <h1>The Scenes</h1>

Advertisement

Answer

What i understood is you want to limit your markdown conversion to a range of 1-6 depth for your title.

Give a try to this code :

function markdown_parser ($markdown) {
    $regex = '/(?:(#+)(.+?)n)|(?:(.+?)ns*=+s*n)/';
    $headerText = $markdown."n";
    $headerText = preg_replace_callback(
        $regex,
        function($matches) use ($markdown){
            if (!preg_match('/s/',$matches[2])) {
                return "#".$matches[2];
            }
            if($matches[1] != ""){
                $h_num = strlen($matches[1]);
                if (in_array($h_num, range(1, 6), true)) {
                    return html_entity_decode("<h$h_num>" . trim($matches[2]) . "</h$h_num>");
                }

                return $markdown;
            }
        },
        $headerText
    );
    return $headerText;
}

I only add a condition to check if your number of hashtag is in range of 1 until 6if (in_array($h_num, range(1, 6), true)) {

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement