preg_replace 可能带有一个或两个参数的简码

preg_replace shortcode which may take one or two arguments

我需要允许用户在我网站的前端使用简码 [warning]。此简码后只能跟一个 [warning](arg1) 或两个参数 [warning](optional-arg)(arg1)。当输入两个参数时,第一个 optional-arg 将被视为标题,第二个 arg1作为 body 文本,如果只输入一个 arg1 它将被视为 body 文本。

这是我正在管理的代码

function warning($text) {
    $text = preg_replace('/\[warning\]\s*\((.*?)\)/', '<div class="alert alert-error"><div class="alert-content">  </div></div>', $text); //for warning with body text only
    $text = preg_replace('/\[warning\]\s*\((.*?)\)\s*\((.*?)\)/', '<div class="alert alert-error"><div class="alert-content"><h2 class="alert-title">  </h2><div class="alert-body"><p>  </p></div></div></div>', $text); //for warning with heading 
    return $text;
}
add_filter('the_content', 'warning');
add_filter( 'the_excerpt', 'warning');

问题是第二个参数没有考虑,不在警告框内

这是 preg_replace_callback

的工作
function warning($text) {
    return preg_replace_callback('/\[warning\]\s*\((.*?)\)(?:\s*\((.+?)\))?/', 
        function ($m) {
            if (isset($m[2])) {
                return '<div class="alert alert-error"><div class="alert-content"><h2 class="alert-title"> '.$m[1].' </h2><div class="alert-body"><p> '.$m[2].' </p></div></div></div>';
            } else {
                return '<div class="alert alert-error"><div class="alert-content"> '.$m[1].' </div></div>';
            }
        }
        , $text);
}
echo warning("[warning](body)"), "\n";
echo warning("[warning](header)(body)"), "\n";

输出:

<div class="alert alert-error"><div class="alert-content"> body </div></div>
<div class="alert alert-error"><div class="alert-content"><h2 class="alert-title"> header </h2><div class="alert-body"><p> body </p></div></div></div>