简体   繁体   中英

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)|(?:(.+?)\n\s*=+\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>

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)|(?:(.+?)\n\s*=+\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 6 if (\\in_array($h_num, \\range(1, 6), true)) {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM