繁体   English   中英

无法使用正则表达式在 php 中标记解析器函数

[英]Failed to markdown parser function in php using regex

让我们编写一个简单的 Markdown 解析器函数,该函数将接收一行 Markdown 并翻译成适当的 HTML。 为简单起见,我们将仅支持 atx 语法中降价的一项功能:标头。

标头由 (1-6) 个哈希指定,后跟一个空格,然后是文本。 散列的数量决定了 HTML 输出的标题级别。

例子

# Header will become <h1>Header</h1>
## Header will become <h2>Header</h2>
###### Header will become <h6>Header</h6>

我的代码:

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;
}

它不能作为失败的测试用例工作:

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

我的理解是您想将您的降价转换限制在您标题的 1-6 深度范围内。

试试这个代码:

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;
}

我只添加一个条件来检查你的标签数量是否在 1 到 6 的范围内if (\\in_array($h_num, \\range(1, 6), true)) {

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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