1 回答

TA贡献1809条经验 获得超8个赞
我建议不要寻找完美的 RegEx,而是考虑使用preg_replace_callback()。它应该允许您使用更简单的 RegEx,同时更好地控制模板引擎的搜索和替换算法。考虑以下示例:
resolvePlaceholder()
生成替换内容interpolate()
解析模板字符串。它支持多达 4 级的嵌套解析。停止递归解析以 开头的标签
!
。
<?php
function resolvePlaceholder($name)
{
$store = [
'user:first' => 'John',
'user:last' => 'Doe',
'user:full_name' => '{{user:first}} {{user:last}}',
'block:welcome' => 'Welcome {{user:full_name}}',
'variable:system_version' => '2019.1',
'nest-test' => '{{level1}}',
'level1' => '{{level2}}',
'level2' => '{{level3}}',
'level3' => '{{level4}}',
'level4' => '{{level5}}',
'level5' => 'Nesting Limit Test Failed',
'user-template' => 'This is a user template with {{weird-placeholder}} that will not be replaced in edit mode {{user:first}}',
];
return $store[$name] ?? '';
}
function interpolate($text, $level = 1)
{
// Limit interpolation recursion
if ($level > 5) {
return $text;
}
// Replace placeholders
return preg_replace_callback('/{{([^}]*)}}/', function ($match) use ($level) {
list($tag, $name) = $match;
// Do not replace tags with :keep
if (strpos($name, ':keep')) {
// Remove :keep?
return $tag;
}
if (strpos($name, '!') === 0) {
return resolvePlaceholder(trim($name, '!'));
}
return interpolate(resolvePlaceholder($name), $level + 1);
}, $text);
}
$sample = 'Hi, this is a block of text {{block:welcome}} and this is a system variable {{variable:system_version}}. ' .
'This is a placeholder {{variable:web_url:keep}}. Nest value test {{nest-test}}. User Template: {{!user-template}}';
echo interpolate($sample);
// Hi, this is a block of text Welcome John Doe and this is a system variable 2019.1. This is a placeholder {{variable:web_url:keep}}. Nest value test {{level5}}. User Template: This is a user template with {{weird-placeholder}} that will not be replaced in edit mode {{user:first}}
- 1 回答
- 0 关注
- 125 浏览
添加回答
举报