无法使用regex标记php中的语法分析器函数



让我们编写一个简单的markdown解析器函数,该函数将接收一行markdown,并将其转换为适当的HTML。为了简单起见,我们只支持atx语法中markdown的一个特性:headers。

标头由(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)|(?:(.+?)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;
}

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

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)|(?:(.+?)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;
}

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

最新更新