【问题标题】:(Php) BBcode same tag in tag interesting nested problem(Php) 标签中的 BBcode 相同标签有趣的嵌套问题
【发布时间】:2022-01-31 09:03:55
【问题描述】:

这是我的功能。

class bbcode{
    var $bbcode_bb2html;
    function __construct($string){
            $this->bbcode_bb2html= $string;
    }
    function bbcode_parse_codes( ){
            $this->bbcode_bb2html = preg_replace("#\[code=(.*?)\](.*?)\[/code\]#si", "<pre data-snap-ignore=true class=language-\\1><code>\\2</code></pre>", $this->bbcode_bb2html);
            return $this->bbcode_bb2html;
    }
}
$content="[code=php]test message[/code]";
$bbcode = new bbcode($content);
echo $bbcode->bbcode_bb2html();   

真实结果

<pre data-snap-ignore=true class=language-php><code>test message</code></pre>

但嵌套消息不起作用。样品;

$content="[code=php]test message [code=php]...[/code] bla bla bla[/code]";
$bbcode = new bbcode($content);
echo $bbcode->bbcode_bb2html(); 

错误结果

&lt;pre data-snap-ignore=true class=language-php&gt;&lt;code&gt;test message [code=php]...&lt;/code&gt;&lt;/pre&gt; bla bla bla[/code]

【问题讨论】:

  • 函数 bbcode_bb2html(){ if ( empty($this->bbcode_bb2html) ){ return ( false ); } $this->bbcode_parse_codes( );返回 $this->bbcode_bb2html; }

标签: php html nested preg-replace bbcode


【解决方案1】:

你可以使用

\[code=([^]]*)]([^[]*(?:\[(?!/code]|code=)[^[]*)*)\[/code]

并替换直到找不到匹配项。请参阅regex demo详情

  • \[code= - [code= 字符串
  • ([^]]*) - 第 1 组:除 ] char 之外的任何零个或多个字符
  • ] - 一个 ] 字符
  • ([^[]*(?:\[(?!/code]|code=)[^[]*)*) - 第 2 组:除 [ 字符外的任何零个或多个字符,然后出现零个或多个 [ 字符,其后不紧跟 /code]code=,然后是零个或多个字符除了[ char
  • \[/code] - [/code] 字符串。

PHP code,它看起来像

<?php

$text = '[code=php]test message [code=php]...[/code] bla bla bla[/code]';
$repl = '<pre data-snap-ignore=true class=language-$1><code>$2</code></pre>';
$count = 0;
do {
    $text = preg_replace('~\[code=([^]]*)]([^[]*(?:\[(?!/code]|code=)[^[]*)*)\[/code]~', $repl, $text, -1, $count);
} while ($count > 0);
echo $text;

输出:

<pre data-snap-ignore=true class=language-php><code>test message <pre data-snap-ignore=true class=language-php><code>...</code></pre> bla bla bla</code></pre>

只获取可以使用的周围标签

(?s)\[code=([^]]*)]((?:(?!\[/?code\b).|(?R))*)\[/code]

this regex demo。在 PHP 中:

preg_replace('~\[code=([^]]*)]((?:(?!\[/?code\b).|(?R))*)\[/code]~s', $repl, $text)

【讨论】:

  • 你的答案应该是这样的,
    测试消息[code=php]...[/code] bla bla bla
  • @ulusanyazilim 最后你仍然需要将所有这些代码转换为 html,不是吗?
  • 不,只有第一个和最后一个标签
  • @ulusanyazilim 然后使用正则表达式递归。
  • 示例 bbcode [code]asd[code]asd[/code]asd[/code] 你的代码输出
    asd<pre>asd pre>asd
    我想变成这样
    asd[code]asd[/code]asd
猜你喜欢
  • 1970-01-01
  • 2013-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-06
相关资源
最近更新 更多