正则表达式将[quote =" author"] text [/ quote]转换为格式化的div块

时间:2016-01-25 03:06:52

标签: php html regex

我试图将[quote="author"]text[/quote]转换为格式化的div块。

function bbCode($p_text){

      // capture author

      $pattern = '/\[quote="(.+)"\]/';
      preg_match($pattern, $p_text, $match);

      // replace bbcode with formatted block

      $patternA = '/\[quote=".+"\]/'; // captures [quote="..."]
      $replacementA = '</p><div class="quote"><strong class="quote-author"><?php echo $match; ?> wrote:</strong><br>';
      $p_text = preg_replace($patternA, $replacementA, $p_text);

      $patternB = '/\[\/quote\]/'; // captures [/quote]
      $replacementB = '</div><p class="thread-p">';
      $p_text = preg_replace($patternB, $replacementB, $p_text);

      return $p_text;

}

在主文件中:

<?php 

// $p_text is defined before this
$p_text = bbCode($p_text); 

?>

<p class="thread-p"><?php echo $p_text; ?></p>

似乎只是提出了[quote="author"]text然后div关闭了下面html的其他部分。不确定我做错了什么。

我已经尝试结束<p>,因为div不能进入<p>的iirc,也许这会搞砸什么?

1 个答案:

答案 0 :(得分:0)

我理解你的问题是你想要

  

[报价=&#34;作者&#34;]文本[/报价]

并创建将显示作者和文本的HTML。

这是一种可能的实施方式:

<?php
function bbCode($p_text) {
        $pattern = '#\[quote="([^\"]+)"\]([^\[]+)\[/quote\]#';
        preg_match_all($pattern,$p_text,$matches);
        $html = <<< HTML
<div class="quote">
        <span class="quote-author">__AUTHOR__ wrote:</span>
        <p>__QUOTE__</p>
</div>
HTML;
        return str_replace(['__AUTHOR__','__QUOTE__'],[$matches[1][0],$matches[2][0]], $html);

}
echo bbCode('[quote="author"]text[/quote]');