preg_replace 多个问题

preg_replace issue on multiple

目前我得到这个结果https://puu.sh/zvWLl/1db4614184.png 来自这组代码:

$CheckArrays = [
"QUOTE" => "/\[quote=?(.*)\](.*)\[\/quote\]/",
"BOLD" => "/\[b\](.*)\[\/b\]/",
"ITALIC" => "/\[i\](.*)\[\/i\]/",
];

$FanceString = $UglyString;

// QUOTES
do {
    $FanceString = preg_replace_callback(
        $CheckArrays['QUOTE'],
        function($match) {
            if (is_numeric($match[1])) {
                $TPID = GetThreadPoster($match[1]);
                $TPUN = GetUsernameS($TPID);
                $statement = ('<div class="panel panel-default"><div class="panel-heading">'.$match[2].'<br>- <b>'.$TPUN.'</b></div></div>');
            } elseif (!is_numeric($match[1])) {
                $statement = ('<div class="panel panel-default"><div class="panel-heading">'.$match[2].'</div></div>');
            }
            return $statement;
        },
        $FanceString,
        -1,
        $count
    );
} while ($count > 0);

我的测试字符串是:

[quote=82][quote=76]Isn't that the true ultimate question?[/quote]
[b]I suppose, if that [b]test[/b] makes you feel better[/b][/quote]


This is a test

基本上,这就是我想要实现的目标.. https://puu.sh/zvWVs/c27663e0ac.png

我将在这里展示我的解决方案,但您实际上应该改用解析器。对于您的具体情况,您可以使用递归方法:

\[b[^][]*\]
(?:[^][]*|(?R))*
\[/b\]

参见a demo on regex101.com


PHP 代码为:

<?php

$data = <<<DATA
[quote=82][quote=76]Isn't that the true ultimate question?[/quote]
[b]I suppose, if that [b]test[/b] makes you feel better[/b][/quote]


This is a test
DATA;

$outer = '~
                \[b[^][]*\]
                (?:[^][]*|(?R))*
                \[/b\]
                ~x';

$inner = '~\[/?[^][]*\]~';
$data = preg_replace_callback(
    $outer,
    function($match) use ($inner) {
        return "<strong>" . preg_replace($inner, '', $match[0]) . "</strong>";
    },
    $data);

echo $data;
?>

产生

[quote=82][quote=76]Isn't that the true ultimate question?[/quote]
<strong>I suppose, if that test makes you feel better</strong>[/quote]


This is a test