Blockquote Markdown语法

时间:2013-10-14 23:10:22

标签: php regex preg-replace markdown

我想将blockquotes添加到我的解析器中,比如Stack Overflow,其中>用于标记块引用的一部分。

以下是我正在开展的课程:

<?php

$string = "This is a paragraph

> This is a blockquote
> This is a blockquote
> This is a blockquote

This is another paragraph
";
$md = new Markdown();
echo $md->parseString($string);

这是我在类中解析块引用的问题,问题是,它找不到我想要引用的部分。

<?php
$this->string = preg_replace("/^>(.+?)/is", "<blockquote>$1</blockquote>", $this->string);

如何找到这些多行程序段引用?

2 个答案:

答案 0 :(得分:1)

您可以使用/(?:^>.+\n)+/m进行回调替换,然后在回调中使用此/^>/m返回$ match [0]的结果,“”

 return '<blockquote>' + preg_replace( '/^>/m', "", $match[0] ) + '</blockquote>';

(我是php的新手)

答案 1 :(得分:0)

你可以这样做:

$subject = <<<'LOD'
This is a paragraph

> This is a blockquote
> This is a blockquote
> This is a blockquote

This is another paragraph
LOD;

$pattern = '~(?<=(\n)|)\R> (.*)(?=(\R> )?)~';

$result = preg_replace_callback($pattern, function ($match) {
    $before = (empty($match[1])) ? '' : '<blockquote>';
    $after  = (empty($match[3])) ? '</blockquote>' : '';
    return  $before . $match[2] . $after; }, $subject);

print_r($result);