preg_replace шорткод, который может принимать один или два аргумента - PullRequest
0 голосов
/ 04 марта 2019

Мне нужно разрешить пользователям использовать короткий код [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');

Проблема в том, что второй аргумент не рассматривается и отсутствуетокна предупреждения.

1 Ответ

0 голосов
/ 04 марта 2019

Это задание для 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>
...