php - 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');
问题是第二个参数没有被考虑并且超出了警告框。
解决方案
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>
推荐阅读
- powerpoint - 选择部分缩放矩形而不单击(powerpoint)
- css - post-css 找不到来自 node_modules 的路径
- powershell - 使用 Powershell 通过 IE 使用 JavaScript 时的空文档
- php - liip_imagine [在 Sylius 内] 不在 linux 上缓存图像
- python-3.x - 如果初始条件触发终端 = True 的事件,Solve_ivp 积分会卡住
- xpath - 根据部分匹配机器人查找父元素(不是直接父元素),包括父 ID 和子值
- angular - 在 Angular 中安装 FullCalendar
- azure-web-app-service - 根据验证程序,模板部署“Microsoft.Web-WebApp-Portal-3994ede8-a307”无效
- mysql - mysql 授予除系统表之外的所有表的权限
- data-modeling - 允许用户编辑数据和批准者批准或拒绝更改的逻辑数据模型