doukoumi3389 2014-12-28 04:40
浏览 303
已采纳

[bb]中的php bbcode解析器[tag]

I have simple BBCode parser:

function parse($text) {
    $text = htmlspecialchars($text);
    $text = nl2br($text);
    $text = preg_replace("#\[b\](.*?)\[/b\]#si", '<b>\\1</b>', $text);
    $text = preg_replace("#\[i\](.*?)\[/i\]#si", '<i>\\1</i>', $text);
    $text = preg_replace("#\[u\](.*?)\[/u\]#si", '<u>\\1</u>', $text);
    $text = preg_replace("#\[color=(.*?)\](.*?)\[/color\]#si", "<span style=\"color:\\1;\">\\2</span>", $text);
//and some more rules [...]
    return $text;
}

It work's good when i have simple input, but when user trying use color in color, it's not working.

For example 1:

[b]bold[color=#f00]red[/color][i]italic[/i][/b]

everything is OK, but when user try something like example 2:

[b]bold[color=#f00]red[color=#0f0]green[/color][/color][i]italic[/i][/b]

my function returns:

<b>bold<span style="color:#f00;">red[color=#0f0]green</span>[/color]<i>italic</i></b>

of course example 3 working good:

[b]bold[color=#f00]red[/color][color=#0f0]green[/color][i]italic[/i][/b]

My question is it any simple solution to build something like DOM and then parse expresion? I'd like get something like this for 2nd example:

<b>bold<span style="color:#f00;">red<span style="color:#0f0;">green</span></span><i>italic</i></b>
  • 写回答

1条回答 默认 最新

  • dqayok7935 2014-12-28 04:57
    关注

    You should look into already existing solutions if you're willing to parse complex BBCode (see the post mario linked in a comment for reference).

    However, if you're willing to stick with your own implementation, you can use recursive regexes, for example this way:

    <?php
    function bbcodeColor($input)
    {
        $regex = '#\[color=(.*?)\](((?R)|.)*?)\[\/color\]#is';
        if (is_array($input)) {
            $input = '<span style="color:'.$input[1].';">'.$input[2].'</span>';
        }
        return preg_replace_callback($regex, 'bbcodeColor', $input);
    }
    
    echo bbcodeColor('[color=#f00]red[color=#0f0]green[/color][/color]');
    // <span style="color:#f00;">red<span style="color:#0f0;">green</span></span>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀