【问题标题】:SyntaxHighlighter BBCode PHPSyntaxHighlighter BBCode PHP
【发布时间】:2012-10-23 18:55:06
【问题描述】:

我创建的用于SyntaxHighlighter 的 BBCode 存在一些问题

function bb_parse_code($str) {
    while (preg_match_all('`\[(code)=?(.*?)\]([\s\S]*)\[/code\]`', $str, $matches)) foreach ($matches[0] as $key => $match) {
        list($tag, $param, $innertext) = array($matches[1][$key], $matches[2][$key], $matches[3][$key]); 
        switch ($tag) {
            case 'code': $replacement = '<pre class="brush: '.$param.'">'.str_replace("    ", " ", str_replace(array("<br>", "<br />"), "\n", $innertext))."</pre>"; break;

        }
        $str = str_replace($match, $replacement, $str);
    }
    return $str;
}

我有 bbcode:

[b]bold[/b]
[u]underlined[/u]
[code=js]function (lol) {
alert(lol);
}[/code]
[b]bold2[/b]
[code=php]
<? echo 'lol' ?>
[/code]

返回这个:

我知道问题出在允许任何字符的正则表达式的([\s\S]*) 上,但是如何使代码与换行符一起工作?

【问题讨论】:

  • 对于简单的情况,您可以使用(.*?),这是一个不贪婪的匹配。
  • .*? 不适用于休息...

标签: php regex syntax-highlighting bbcode


【解决方案1】:

您应该使用以下模式:

`\[(code)=?(.*?)\](.*?)\[/code\]`s

一些变化:

【讨论】:

    猜你喜欢
    • 2011-04-15
    • 1970-01-01
    • 2012-03-04
    • 1970-01-01
    • 2012-09-03
    • 1970-01-01
    • 2011-03-14
    • 2012-05-21
    相关资源
    最近更新 更多