首页 > 解决方案 > preg_replace 短代码,可能带有一个或两个参数

问题描述

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

这是我正在管理的代码

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

问题是第二个参数没有被考虑并且超出了警告框。

标签: phppreg-replace

解决方案


这是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>

推荐阅读