php preg_replace_callback blockquote regex

时间:2018-02-17 20:05:12

标签: php regex

我正在尝试创建一个

的REGEX

Input

> quote
the rest of it

> another paragraph
the rest of it

OUTPUT

报价 剩下的了

另一段 剩下的了

结果 HTML

<blockquote>
<p>quote
the rest of it</p>
<p>another paragraph
the rest of it</p>
</blockquote>

这就是我在下面的内容

$text = preg_replace_callback('/^>(.*)(...)$/m',function($matches){
    return '<blockquote>'.$matches[1].'</blockquote>';
},$text);

DEMO

任何帮助或建议都将不胜感激

2 个答案:

答案 0 :(得分:1)

以下是给定示例的可能解决方案。

$text = "> quote
the rest of it

> another paragraph
the rest of it";


preg_match_all('/^>([\w\s]+)/m', $text, $matches);

$out = $text ;
if (!empty($matches)) {
    $out = '<blockquote>';
    foreach ($matches[1] as $match) {
        $out .= '<p>'.trim($match).'</p>';
    }
    $out .= '</blockquote>';
}

echo $out ;

输出:

<blockquote><p>quote 
the rest of it</p><p>another paragraph
the rest of it</p></blockquote>

答案 1 :(得分:0)

试试这个正则表达式:

(?s)>((?!(\r?\n){2}).)*+

含义:

(?s)           # enable dot-all option
b              # match the character 'b'
q              # match the character 'q'
\.             # match the character '.'
(              # start capture group 1
  (?!          #   start negative look ahead
    (          #     start capture group 2
      \r?      #       match the character '\r' and match it once or none at all
      \n       #       match the character '\n'
    ){2}       #     end capture group 2 and repeat it exactly 2 times
  )            #   end negative look ahead
  .            #   match any character
)*+            # end capture group 1 and repeat it zero or more times, possessively

\r?\n匹配Windows,* nix和(较新的)MacOS换行符。如果您需要考虑真正的旧Mac计算机,请为其添加单个\r\r?\n|\r

问题:https://stackoverflow.com/a/2222331/9238511